这是Java并发编程中提到的一个简单的缓存系统,不是本人代码哦,我还没有这么高的水平。。:)
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
interface Computable<K,V>{
V compute(final K arg);
}
/**
* 实现简单缓存系统
* @author mzy
*
* @param <K> key
* @param <V> value
*/
public class FutureCache<K,V> implements Computable<K,V>{
private final ConcurrentHashMap<K, Future<V>> cache = new ConcurrentHashMap<K ,Future<V>>();
private final Computable<K, V> c;
public FutureCache(Computable<K, V> c) {
this.c = c;
}
@Override
public V compute(final K key) {
while(true){
Future<V> future = cache.get(key);
if(future == null){
Callable<V> eval = new Callable<V>() {
@Override
public V call() throws Exception { return c.compute(key); }
};
FutureTask<V> ftask = new FutureTask<V>(eval);
//使用putIfAbsent原子操作避免有上面if(future == null)引起的相同值的缺陷
future = cache.putIfAbsent(key, ftask);
if(future == null) { future = ftask; ftask.run(); }
}
try {
return future.get();
} catch (InterruptedException e) {
//出现中断异常应该从 cache中移除Future,防止缓存污染
cache.remove(key,future);
} catch (ExecutionException e) {
//执行中的异常应当抛出,获得恰当处理
throw new RuntimeException(e.getCause());
}
}
}
}
下面是一个测试类:
public class Test {
public static void main(String[] args) {
final Computable<Integer, Integer> c = new Computable<Integer, Integer>() {
@Override
public Integer compute(Integer arg) {
Integer sum = 0;
for(Integer i=0;i<arg;i++){
sum+=i;
}
return sum;
}
};
final Computable<Integer, Integer> cache = new FutureCache<Integer,Integer>(c);
long start = System.currentTimeMillis();
cache.compute(10000);
long stop = System.currentTimeMillis();
System.out.println(stop-start);
start = System.currentTimeMillis();
cache.compute(10000);
stop = System.currentTimeMillis();
System.out.println(stop-start);
start = System.currentTimeMillis();
cache.compute(10000);
stop = System.currentTimeMillis();
System.out.println(stop-start);
start = System.currentTimeMillis();
cache.compute(10000);
stop = System.currentTimeMillis();
System.out.println(stop-start);
}
}
@绝望的八皮