Skip to content

Instantly share code, notes, and snippets.

@CrypticMessenger
Created October 2, 2025 07:29
Show Gist options
  • Save CrypticMessenger/9ff799b6c28727e66e3dd71dcf263ed5 to your computer and use it in GitHub Desktop.
Save CrypticMessenger/9ff799b6c28727e66e3dd71dcf263ed5 to your computer and use it in GitHub Desktop.
/**
* Iteration 4: Future-Based Safe Memoizer
* A thread-safe implementation of a memoizer that caches computed results using Future.
* This class implements the Computable interface and provides a caching mechanism
* to store and reuse previously computed results.
*/
public class FutureSafeMemoizer<A, V> implements Computable<A, V> {
private final Map<A, Future<V>> cache = new ConcurrentHashMap<>();
private final Computable<A, V> computable;
public FutureSafeMemoizer(Computable<A, V> computable) {
this.computable = computable;
}
@Override
public V compute(A arg) throws InterruptedException {
Future<V> future = cache.get(arg);
if (future == null) {
Callable<V> eval = new Callable<V>() {
public V call() throws InterruptedException {
return computable.compute(arg);
}
};
FutureTask<V> ft = new FutureTask<V>(eval);
future = ft;
cache.put(arg, ft);
ft.run(); // call to c.compute happens here
}
try {
return future.get();
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment