JAVA使用JDK1.5提供的讀寫鎖實現高併發本地快取工具類
阿新 • • 發佈:2019-09-13
package com.study;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class ReadWriteLockDemo {
private static Map<String, Object> cacheMap = new LinkedHashMap<String, Object>();
public static void main(String[] args) {
ReadWriteLockDemo readWriteLockDemo = new ReadWriteLockDemo();
final CacheUtils cacheUtils = readWriteLockDemo.new CacheUtils();
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
for(Integer index = 0;index <= 100;index ++){
System.out.println(cacheUtils.putCache(index.toString()));
}
}
});
thread.start();
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
for(Integer index = 0;index <= 100;index ++){
System.out.println(cacheUtils.putCache(index.toString()));
}
}
});
thread2.start();
}
class CacheUtils {
// 定義一把讀寫鎖
ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
public Object putCache(String key){
//進來時,先用讀鎖進行上鎖
readWriteLock.readLock().lock();
Object value = null;
try {
value = cacheMap.get(key);
if(value == null){
readWriteLock.readLock().unlock();
try {
readWriteLock.writeLock().lock();
if(value == null){
//此處實際上是查詢DB
value = "huangkejie" + key;
cacheMap.put(key, value);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
readWriteLock.writeLock().unlock();
}
readWriteLock.readLock().lock();
}
} catch (Exception error) {
error.printStackTrace();
} finally{
readWriteLock.readLock().unlock();
}
return value;
}
}
}