Skip to content

Instantly share code, notes, and snippets.

@CrypticMessenger
Created October 2, 2025 07:05
Show Gist options
  • Save CrypticMessenger/eff37ba303268ea69851e8bb4a71b041 to your computer and use it in GitHub Desktop.
Save CrypticMessenger/eff37ba303268ea69851e8bb4a71b041 to your computer and use it in GitHub Desktop.
/**
* 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