Java Concurrency Program · CD10
Thread-Safe Cache with ConcurrentHashMap in Java
A check-then-put cache has a race: two threads both see a miss and both load the value. computeIfAbsent() makes the check and the load one atomic step.
Problem Statement
Ten threads ask a cache for "user:42" at the same moment. Loading the profile from the database is slow and must happen only once.
Every thread must receive the same cached object.
Input/Output Examples
10 threads, empty cacheOutputvalue loaded 1 timeExplanation: the other 9 threads wait for the first load.compare the returned objectsOutputall the same objectExplanation: the cache stores and returns one instance.get(); if null, load and put()Outputloaded up to 10 timesExplanation: the check and the put are separate steps.Visual Explanation
- 10 threadsaskuser:42cache is empty
- Thread 1loads200 mscomputeIfAbsent() runs the loader
- Threads 2-10waitsame keyno second load loader runs once
- Done1 load, 1 object
The loader must be quick enough to run inside the map's internal lock for that key, and it must never update the same map.
Approaches
Both approaches load each key exactly once. The first relies on computeIfAbsent(); the second stores futures so the slow load runs outside any map lock.
Approach 1: computeIfAbsent() (Recommended)
Idea: call cache.computeIfAbsent(key, loader); ConcurrentHashMap runs the loader at most once per key and stores the result atomically.
- Keep a
ConcurrentHashMap<String, String>. - Return
cache.computeIfAbsent(key, UserCache::loadFromDatabase). - Count the loads to prove that the loader ran once.
Time: O(1) average · Space: O(k). k is the number of cached keys; the first call also pays the load time.
Approach 2: Cache of Futures
Idea: store a CompletableFuture per key with putIfAbsent(); the winner loads and completes it, the others join() it.
- Create a new, empty future.
- Try
putIfAbsent(key, mine); if another future is already there, join it. - Otherwise load the value and complete your future.
Time: O(1) average · Space: O(k).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Thread timing changes from run to run, so the programs print checks (true or false) instead of raw milliseconds; both tabs print the same output.
Approach 1: computeIfAbsent() (Recommended)
One line, correct, and what interviewers usually expect.
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
public class CacheComputeIfAbsent {
static class UserCache {
static final AtomicInteger loads = new AtomicInteger();
private final Map<String, String> cache = new ConcurrentHashMap<>();
// computeIfAbsent() runs the loader at most once per key, even when threads race
String get(String key) {
return cache.computeIfAbsent(key, UserCache::loadFromDatabase);
}
private static String loadFromDatabase(String key) {
loads.incrementAndGet();
try {
Thread.sleep(200); // slow load
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return new String("profile of " + key); // a new object each time it is loaded
}
}
public static void main(String[] args) throws InterruptedException {
UserCache cache = new UserCache();
int threads = 10;
CountDownLatch start = new CountDownLatch(1);
Set<Integer> identities = ConcurrentHashMap.newKeySet();
List<Thread> list = new ArrayList<>();
for (int i = 0; i < threads; i++) {
Thread t = new Thread(() -> {
try {
start.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
identities.add(System.identityHashCode(cache.get("user:42")));
});
list.add(t);
t.start();
}
start.countDown(); // all threads ask at the same moment
for (Thread t : list) {
t.join();
}
System.out.println(threads + " threads read \"user:42\"");
System.out.println("value loaded " + UserCache.loads.get() + " time(s)");
System.out.println("all threads got the same object: " + (identities.size() == 1));
}
}
10 threads read "user:42" value loaded 1 time(s) all threads got the same object: true
Time complexity: O(1) average · Space complexity: O(k).
Approach 2: Cache of Futures
The slow load runs outside the map's locks, which matters when loads are long or call other caches.
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.CompletableFuture;
public class CacheFutureMemo {
static class UserCache {
static final AtomicInteger loads = new AtomicInteger();
private final Map<String, CompletableFuture<String>> cache = new ConcurrentHashMap<>();
// Store a future instead of the value: the first thread loads it, the others wait on the same future
String get(String key) {
CompletableFuture<String> mine = new CompletableFuture<>();
CompletableFuture<String> existing = cache.putIfAbsent(key, mine);
if (existing != null) {
return existing.join();
}
mine.complete(loadFromDatabase(key)); // the loading happens outside any map lock
return mine.join();
}
private static String loadFromDatabase(String key) {
loads.incrementAndGet();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return new String("profile of " + key);
}
}
public static void main(String[] args) throws InterruptedException {
UserCache cache = new UserCache();
int threads = 10;
CountDownLatch start = new CountDownLatch(1);
Set<Integer> identities = ConcurrentHashMap.newKeySet();
List<Thread> list = new ArrayList<>();
for (int i = 0; i < threads; i++) {
Thread t = new Thread(() -> {
try {
start.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
identities.add(System.identityHashCode(cache.get("user:42")));
});
list.add(t);
t.start();
}
start.countDown(); // all threads ask at the same moment
for (Thread t : list) {
t.join();
}
System.out.println(threads + " threads read \"user:42\"");
System.out.println("value loaded " + UserCache.loads.get() + " time(s)");
System.out.println("all threads got the same object: " + (identities.size() == 1));
}
}
10 threads read "user:42" value loaded 1 time(s) all threads got the same object: true
Time complexity: O(1) average · Space complexity: O(k).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| computeIfAbsent() | O(1) average | O(k) |
| Cache of Futures | O(1) average | O(k) |
Lookups take O(1) time on average. Each key costs one load, no matter how many threads ask for it.
Interview Tips and Recommended Approach
- Point out the race in the naive
get()thenput()version before fixing it. - Keep the loader short and never modify the same map inside it.
- Mention eviction. This cache grows forever; real caches add a size limit or expiry.
- Know the libraries. Caffeine and Guava caches provide loading, expiry and eviction ready-made.
Recommended Approach: computeIfAbsent()
Why: it solves the race in one atomic call and needs no extra classes. Move to futures when loads are slow enough to hold up other keys.