Created
September 30, 2025 18:47
-
-
Save CrypticMessenger/9e0cb502c81f6ad5cf34ba8d34fc5752 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 2: Serialized Naive Safe Memoizer | |
| * A thread-safe implementation of a memoizer that caches computed results. | |
| * This implementation synchronizes the entire compute method, ensuring thread safety | |
| * but potentially creating performance bottlenecks under high contention. | |
| */ | |
| public class SerializedNaiveSafeMemoizer<A,V> implements Computable<A,V> { | |
| @GuardedBy("this") // documents that cache is protected by the intrinsic lock | |
| private final Map<A,V> cache = new HashMap<>(); | |
| private final Computable<A,V> computable; | |
| public SerializedNaiveSafeMemoizer(Computable<A,V> computable) { | |
| this.computable = computable; | |
| } | |
| // Notice synchronized keyword here | |
| @Override | |
| public synchronized 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