V compute(A arg) throws InterruptedException;
}
public class ExpensiveFunctuion implements Computable<String, Integer> {
public Integer compute(String arg) throws InterruptedException {
//do..............
return new Integer(arg);
}
}
public class Memoizer3<A, V> implements Computable<A, V> {
private final ConcurrentMap<A, FutureTask<V>> cache = new ConcurrentHashMap<A, FutureTask<V>>();
private final Computable<A, V> c;
// performance is good
public V compute(final A arg) throws InterruptedException {
FutureTask<V> f = cache.get(arg);
if (f == null) {
Callable eval = new Callable() {
public Object call() throws Exception {
return c.compute(arg);
}
};
FutureTask<V> ft = new FutureTask<V>(eval);
f = cache.putIfAbsent(arg, ft);
if(f==null){
f=ft;
ft.run();
}
ft.run();
}
try {
return f.get();
} catch (Exception e) {
cache.remove(arg,f);
}
return null;
}
public Memoizer3(Computable<A, V> c) {
this.c = c;
}
}