Memoization Implementation in Java
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Memoization runs in O(1) cached time and O(n) space, in Java as in every other language.
- ✓ConcurrentHashMap.computeIfAbsent(key, mappingFunction) is atomic memoization in a single call: the mapping function runs at most once per absent key, and other threads asking for that key block until it returns.
- ✓computeIfAbsent on a ConcurrentHashMap for the general case, and Caffeine's LoadingCache when the memo table needs bounding, expiry or refresh, which in a long-lived service it always eventually does.
- ✓The Java trap: Calling computeIfAbsent RECURSIVELY on the same map, the natural shape for memoized recursion, is illegal.
- ✓computeIfAbsent locks only the affected bin, so unrelated keys proceed in parallel and throughput scales with core count.
What Memoization actually is
Memoization in Java: what you actually reach for
Java implementation
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
public final class Memoizer<K, V> {
private final Map<K, V> cache = new ConcurrentHashMap<>();
private final Function<K, V> loader;
public Memoizer(Function<K, V> loader) {
this.loader = loader;
}
// Atomic: the loader runs at most once per absent key.
public V get(K key) {
return cache.computeIfAbsent(key, loader);
}
}
// Memoized RECURSION cannot use computeIfAbsent (IllegalStateException
// "Recursive update" since Java 9), do it explicitly:
public final class Fib {
private final Map<Integer, Long> memo = new ConcurrentHashMap<>();
public long get(int n) {
if (n < 2) return n;
Long hit = memo.get(n);
if (hit != null) return hit;
long value = get(n - 1) + get(n - 2);
memo.putIfAbsent(n, value);
return value;
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Java-specific trap
Performance in Java, beyond the O(1) cached
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Java type or library should I use for Memoization?
ConcurrentHashMap.computeIfAbsent(key, mappingFunction) is atomic memoization in a single call: the mapping function runs at most once per absent key, and other threads asking for that key block until it returns. That atomicity is the reason to prefer it over a get/put pair, and it is a genuinely stronger guarantee than most languages give you for free.
What is the most common Java mistake when implementing Memoization?
Calling computeIfAbsent RECURSIVELY on the same map, the natural shape for memoized recursion, is illegal. Since Java 9 it throws IllegalStateException ("Recursive update"); on Java 8 it could corrupt the map internals or spin forever instead, which was worse. Memoized recursion therefore needs an explicit get/compute/put, accepting that two threads may duplicate work.
How does Memoization actually perform in Java?
computeIfAbsent locks only the affected bin, so unrelated keys proceed in parallel and throughput scales with core count. The mapping function runs while that bin lock is held, so a slow loader blocks every other key that hashes to the same bin, keep loaders short or use Caffeine's asynchronous cache. Boxed keys allocate, as everywhere in Java collections. Time complexity is O(1) cached and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for Devin, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.