Java用读-写锁来包装Map

内容:利用ReentrantReadWriteLock来包装Map,从而使它能在多个读线程之间被安全分享,并且仍然能避免“读-写”或“写-写”冲突。记住重要的一点是:读-写锁实现的加锁策略中,允许多个读操作同时进行,但每次只允许一个写操作。

public class ReadWriteMap<K, V> {
	private final Map<K, V> map;
	private final ReadWriteLock lock = new ReentrantReadWriteLock();
	private final Lock r = lock.readLock();
	private final Lock w = lock.writeLock();
	
	public ReadWriteMap(Map<K, V> map) {
		this.map = map;
	}
	
	public V put(K key, V value) {
		w.lock();
		System.out.println("获取写锁");
		try {
			return map.put(key, value);
		} finally {
			w.unlock();
			System.out.println("释放写锁");
		}
	}
	
	public V get(K key) {
		r.lock();
		System.out.println("获取读锁");
		try {
			return map.get(key);
		} finally  {
			r.unlock();
			System.out.println("释放读锁");
		}
	}
	
	public static void main(String[] args) throws InterruptedException {
		final Map<Integer, String> map = new HashMap<Integer, String>();
		final ReadWriteMap<Integer, String> readWriteMap = new ReadWriteMap<Integer, String>(map);
		ExecutorService executorService = Executors.newCachedThreadPool();
		for (int i = 0; i <= 10; i++) {
			final int tmp = i;
			executorService.execute(new Runnable() {
				@Override
				public void run() {
					readWriteMap.put(tmp, tmp+"");
				}
			});
			if ((i & 1) == 1) {
				executorService.execute(new Runnable() {
					@Override
					public void run() {
						System.out.println(readWriteMap.get(new Random().nextInt(6)));
					}
				});
			}
		}
		
		executorService.shutdown();
	}
}


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。