Skip to content

Instantly share code, notes, and snippets.

@liuzhengyang
Created March 22, 2016 03:33
Show Gist options
  • Save liuzhengyang/2a34cb1a4b81e50803a5 to your computer and use it in GitHub Desktop.
Save liuzhengyang/2a34cb1a4b81e50803a5 to your computer and use it in GitHub Desktop.
interface Computable<A, V> {
V compute(A a);
}
public class Memorizer<A, V> implements Computable<A, V> {
private final ConcurrentMap<A, Future<V>> cache = new ConcurrentHashMap<>();
private final Computable<A, V> computable;
public Memorizer(Computable<A, V> computable) {
this.computable = computable;
}
@Override
public V compute(A a) {
Future<V> f = cache.get(a);
if (f == null) {
Callable<V> callable = new Callable<V>() {
@Override
public V call() throws Exception {
System.out.println("compute " + a);
return computable.compute(a);
}
};
FutureTask<V> futureTask = new FutureTask<V>(callable);
f = cache.putIfAbsent(a, futureTask);
if (f == null) {
f = futureTask;
futureTask.run();
}
}
try {
return f.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment