/** * 要执行的算法,返回结果v */ public interface Computable<A, V> { public V comput(final A arg); }
/** * 用于缓存数据 */ public class Memoizer<A, V> implements Computable<A, V> { private final ConcurrentMap<A, Future<V>> cache = new ConcurrentHashMap<A, Future<V>>(); private final Computable<A, V> c; private Memoizer(Computable<A, V> c) { this.c = c; } @Override public V comput(final A arg) { while (true) { Future<V> f = cache.get(arg); if (f == null) { Callable<V> eval = new Callable<V>() { @Override public V call() throws Exception { return c.comput(arg); } }; FutureTask<V> ft = new FutureTask<V>(eval); //若没有这个key则put。总是返回oldValue f = cache.putIfAbsent(arg, ft); if (f == null) { f = ft; ft.run(); } } return null; } } }