package cn.itcast.heima;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* 缓存demo
*
* @ClassName: CacheDemo
* @Description: TODO
* @author liuyuan
* @date 2016年8月10日 下午6:53:07
*/
public class CacheDemo {
private Map<String, Object> cache = new HashMap<String, Object>();// 缓存存放的位置
private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();// 读写锁
public Object getData(String key) {
readWriteLock.readLock().lock();// 加读锁
Object value = null;
try {
value = cache.get(key);// 读
if (value == null) {
readWriteLock.readLock().unlock();// 开读锁
readWriteLock.writeLock().lock();// 加写锁
try {
if (value == null) {
value = "abc";// 写:实际代码为从数据库中查询;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
readWriteLock.writeLock().unlock();// 开写锁
}
readWriteLock.readLock().lock();// 加读锁
}
} catch (Exception e) {
e.printStackTrace();
} finally {
readWriteLock.readLock().unlock();// 开读锁
}
return value;
}
}
缓存demo
最新推荐文章于 2024-11-17 22:59:42 发布