线程安全的缓存类简单实现

阅读更多

一个线程安全的缓存类简单实现:

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

public class Cache {
	private Map cacheData = new HashMap();
	private ReadWriteLock rwlock = new ReentrantReadWriteLock();
	
	public Object get(String key) {
		rwlock.readLock().lock();
		Object value = cacheData.get(key);
		try {
			if(value == null) {
				rwlock.readLock().unlock();
				rwlock.writeLock().lock();
				try {
					if(null == (value = cacheData.get(key))) {
						value = ""; //获取实际数据
						cacheData.put(key, value);
					}
				} finally {
					rwlock.writeLock().unlock();
				}
				rwlock.readLock().lock();
			}
		} finally {
			rwlock.readLock().unlock();
		}		
		return value;
	}
}

 

你可能感兴趣的:(缓存,读写锁)