Skip to content

Instantly share code, notes, and snippets.

@CrypticMessenger
Created September 30, 2025 18:47
Show Gist options
  • Save CrypticMessenger/9e0cb502c81f6ad5cf34ba8d34fc5752 to your computer and use it in GitHub Desktop.
Save CrypticMessenger/9e0cb502c81f6ad5cf34ba8d34fc5752 to your computer and use it in GitHub Desktop.
/**
* 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