util.Concurrent-ReadWriteLock

使用ReadWriteLock模拟简单的缓存管理器

 

package thread.lock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * readLock  与 readLock  不互斥
 * readLocak 与  writeLock 互斥
 * writeLock 与  writeLock 互斥
 */
public class CacheManager {
	
	private ReadWriteLock rwl = new ReentrantReadWriteLock();
	
	private Map<String,Object> cache = new HashMap<String,Object>();
	
	public Object getValue(String key) {
		return processCacheData(key);
	}
	
	protected Object processCacheData(String key) {
		rwl.readLock().lock();
		Object obj = null;
		try {
			obj = cache.get(key);
			if(obj==null) {
				//Release read lock before acquiring write lock
				rwl.readLock().unlock();
				rwl.writeLock().lock();
				//check again
				if(obj==null) {
					obj = "get obj from somewhere";
				}
				rwl.readLock().lock();
				rwl.writeLock().unlock();
			}
		} finally {
			rwl.readLock().unlock();
		}
		return obj;
	}
	
}

 

 

你可能感兴趣的:(ReadWriteLock)