package com.ljq.test.thread;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* 设计一个缓存系统
*
*
* @author Administrator
*
*/
public class CacheDemo {
private Map<String, Object> cache = new HashMap<String, Object>();
public static void main(String[] args) {
String key = "name" ;
CacheDemo cacheDemo = new CacheDemo();
System.out.println(cacheDemo.getData(key));
System.out.println(cacheDemo.getData(key));
System.out.println(cacheDemo.getData(key));
}
private ReadWriteLock rwl = new ReentrantReadWriteLock();
public Object getData(String key) {
rwl.readLock().lock();
Object value = null ;
try {
value = cache.get(key);
if (value == null ) {
rwl.readLock().unlock();
rwl.writeLock().lock();
try {
if (value == null ) {
System.out.println( "read data from database" );
value = "张三" ;
cache.put(key, value);
}
} finally {
rwl.writeLock().unlock();
}
rwl.readLock().lock();
} else {
System.out.println( "read data from cache" );
}
} finally {
rwl.readLock().unlock();
}
return value;
}
}
|