高速缓存??
啥意思?
缓存本来就很快了,还要高速?
对的!!!
下列代码实现了读和写的分离,第一次读 和写 的混合,其他读都需要等待的功能。细细斟酌
package com.yhm.testSpringMvc.readWriteLock;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class ReadWriteLockCache {
public static void main(String[] args) {
}
private Map<String, Object> cache = new HashMap<>();
private Object returnObj = null;
private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
public synchronized Object getCacheBySynchronized(String key) {
Object obj = null;
if (returnObj == null) {
returnObj = "查数据库";
}
return obj;
}
public Object getCacheByReadWriteLock(String key) {
readWriteLock.readLock().lock();
try {
returnObj = cache.get(key);
if (returnObj == null) {
readWriteLock.readLock().unlock();
try {
readWriteLock.writeLock().lock();
if (returnObj == null) {
returnObj = "查数据库";//做真正LOAD到缓存的事情
}
} catch (Exception e) {
} finally {
readWriteLock.writeLock().unlock();
}
readWriteLock.readLock().lock();
}
} catch (Exception e) {
} finally {
readWriteLock.readLock().unlock();
}
return returnObj;
}
}
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于