* 一种带有缓存的计算工具
* Created with IntelliJ IDEA.
* User: pingansheng
* Date: 2016/6/1
* Time: 14:29
*/
public class CachedCompute {
interface Computable<A, V> {
V compute(A args) throws InterruptedException , ExecutionException;
}
class CacheComputer<A, V> implements Computable< A, V > {
private final Map<A, Future<V>> cache = new ConcurrentHashMap<>() ;
private Computable< A, V > computer;
public CacheComputer(Computable< A, V > c) {
this .computer = c ;
}
@Override public V compute (A args) throws InterruptedException , ExecutionException {
Future<V> f = cache.get(args);
if (null == f) {
Callable<V> callable = new Callable< V>() {
@Override public V call() throws Exception {
return computer .compute(args) ;
}
};
FutureTask<V > ft = new FutureTask< V>(callable);
f = cache .putIfAbsent(args, ft) ;
if (null == f) {
System. out.println(" 缓存放置成功 ");
f = ft;
ft.run();
}
}
try {
return f.get() ;
} catch (CancellationException e) {
cache.remove(args , f);
} catch (ExecutionException e) {
throw e ;
}
return null;
}
}
CacheComputer cache = new CacheComputer<String , String>( new Computable<String, String>() {
@Override public String compute (String args)
throws InterruptedException , ExecutionException {
return "计算结果";
}
});
public static void main (String[] args) throws Throwable {
CachedCompute compute = new CachedCompute();
System. out.println(compute.cache .compute("key")) ;
}
}