User$Proxy extends User{
private Integer id;
User realUser=null;
getName(){
if(realUser==null){
realUser.session.get(i)
if(realUser==null) throw Exception
}
return realUser.getName();
}
}
-------
//j2se api中ReentrantReadWriteLock类的示例,下面的代码展示了如何利用重入来执行升级缓存后的锁降级
class CachedData {
Object data;volatile boolean cacheValid;
ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
void processCachedData() {
rwl.readLock().lock();
if (!cacheValid) {
// Must release read lock before acquiring write lock
rwl.readLock().unlock();
rwl.writeLock().lock();
// Recheck state because another thread might have acquired
// write lock and changed state before we did.
if (!cacheValid) {
data = ...
cacheValid = true;
}
// Downgrade by acquiring read lock before releasing write lock
rwl.readLock().lock();
rwl.writeLock().unlock(); // Unlock write, still hold read
}
use(data);
rwl.readLock().unlock();
}
}
-----------------------------------------------
public class CacheDemo//缓存
{
private Map<String,Object> cache=new HashMap<String,Object>();
ReadWriteLock rwl=new ReentrantReadWriteLock();
public void process(String key){
rwl.readLock().lock();
Object value=null;
try
{
value=cache.get(key);
if(value==null){
rwl.readLock().unlock();
rwl.writeLock().lock();
if(value==null){
value="aaa";//queryDB 去数据库中查询
if(value!=null){
cache.put(key,value);
}
}
try
{
rwl.writeLock().unlock();
}
catch (Exception e)
{
e.printStackTrace();
}finally{
rwl.writeLock().unlock();
}
rwl.readLock().lock();
}
}
catch (Exception e)
{
e.printStackTrace();
}finally{
rwl.readLock().unlock();
}
}
}