Created
October 2, 2025 07:29
-
-
Save CrypticMessenger/9ff799b6c28727e66e3dd71dcf263ed5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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