package cn.guagua.mobile.common;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.apache.log4j.Logger;
import cn.guagua.mobile.cache.redis.Redis;
/**
* 读写锁控制强制读取缓存同步
* @author shma
* @date 2014-10-11 15:04:28
*/
public class SynchCacheLock<T> {
private static final Logger logger = Logger.getLogger(SynchCacheLock.class);
private static Redis.RedisClient redis1 = new Redis.RedisClient("1");
private ReadWriteLock lock = null;
private Lock readLock = null; // 读锁
private Lock writeLock = null; // 写锁
public SynchCacheLock() {
lock = new ReentrantReadWriteLock();
readLock = lock.readLock();
writeLock = lock.writeLock();
System.out.println(Thread.currentThread().getName() + ">>> cache lock init...");
}
public T getCache(String key, Runnable task) {
T obj = null;
readLock.lock();
try {
obj = (T) redis1.getObject(key);
if(obj == null) {
System.out.println(Thread.currentThread().getName() + " read request " + key + " is null, wait query...");
readLock.unlock();
writeLock.lock();
try {
obj = (T) redis1.getObject(key);
if(obj == null) {
task.run();//强制执行执行写缓存任务
System.out.println(Thread.currentThread().getName() + " read request " + key + " end...");
obj = (T) redis1.getObject(key);
}
} catch(Throwable e) {
System.out.println("readLock error...");
e.printStackTrace();
} finally {
readLock.lock();
writeLock.unlock();
}
}
System.out.println(Thread.currentThread().getName() + " read request " + key + " data...");
} catch(Throwable e) {
System.out.println("lock error...");
e.printStackTrace();
} finally {
readLock.unlock();
}
return obj;
}
}
读写锁控制缓存失效照成的Dogpile效应
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 前言 相信磁盘缓存在绝大部分的app上都有应用,相对于数据库缓存来说,可以不要注重于缓存的管理,比较开放和随意。再...
- ReadWriteLock是读写分离锁,它可以有效的帮助减少锁竞争,提升系统性能。比如线程A1、A2、A3进行写操...