Created
October 2, 2025 07:05
-
-
Save CrypticMessenger/eff37ba303268ea69851e8bb4a71b041 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 3: Fine-Grained Safe Memoizer | |
| * A thread-safe implementation of a memoizer that caches computed results using fine-grained locking. | |
| * This implementation uses ConcurrentHashMap to allow concurrent access to the cache, | |
| * enabling multiple threads to compute and cache results simultaneously without blocking each other. | |
| */ | |
| public class FineGrainedSafeMemoizer<A,V> implements Computable<A,V> { | |
| private final ConcurrentHashMap<A,V> cache = new ConcurrentHashMap<>(); | |
| private final Computable<A,V> computable; | |
| public FineGrainedSafeMemoizer(Computable<A,V> computable) { | |
| this.computable = computable; | |
| } | |
| @Override | |
| public V compute(A arg) throws InterruptedException { | |
| V result = cache.get(arg); | |
| if (result == null) { | |
| result = computable.compute(arg); | |
| cache.put(arg, result); | |
| } | |
| return result; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment