Scrivio Interview library

Concurrent collections

24 questions in 6 subtopics.

ConcurrentHashMap internals

ConceptFoundations6 min read
What were segments in Java 7's ConcurrentHashMap, what replaced them in Java 8, and what does the concurrencyLevel constructor argument do today?
InternalsFoundations8 min read
How does ConcurrentHashMap in Java 8 and later make put and get thread-safe without one global lock?
InternalsIntermediate7 min read
Explain how ConcurrentHashMap resizes while other threads keep reading and writing.
CodingIntermediate7 min read
Find the race conditions and rewrite:
ConcurrentHashMap<String,Integer> counts = new ConcurrentHashMap<>();
void hit(String k){
if (!counts.containsKey(k)) counts.put(k, 0);
counts.put(k, counts.get(k) + 1);
}
DebuggingIntermediate7 min read
A rate limiter rejects requests when activeSessions.size() >= 1000, where activeSessions is a ConcurrentHashMap. Under load the service sometimes holds 1,050 sessions. Why, and how would you enforce the limit?
DesignAdvanced7 min read
Your platform team provides an in-memory registry (routing table and feature flags) used by many services, read on every request and updated a few times a minute from a control plane. Choose between a ConcurrentHashMap updated in place and an immutable snapshot replaced atomically, and define the consistency guarantees.

ComputeIfAbsent pitfalls

DebuggingFoundations7 min read
This memoized Fibonacci works for small n but fails for larger n on Java 9+ with IllegalStateException: Recursive update. Why?
Map<Integer, Long> memo = new ConcurrentHashMap<>();
long fib(int n){
if (n < 2) return n;
return memo.computeIfAbsent(n, k -> fib(k - 1) + fib(k - 2));
}
InternalsIntermediate7 min read
On Java 8, profiling showed threads contending inside ConcurrentHashMap.computeIfAbsent even when the key was always present. What was the cause, what is the usual workaround, and does it still apply on newer JDKs?
ScenarioIntermediate7 min read
A team caches remote lookups with cache.computeIfAbsent(userId, id -> userClient.fetch(id)) on a ConcurrentHashMap. When the user service is slow, unrelated cache reads and writes also stall. Explain and redesign.
DesignAdvanced7 min read
Multiple services call an expensive pricing API and each instance memoizes results per product id. During cache expiry, hundreds of concurrent requests for the same product hit the API at once. Design a standard approach for request coalescing and memoization that teams can reuse.
LeadershipPrincipal6 min read
ConcurrentHashMap.computeIfAbsent has a contract the compiler cannot check: the function must be short and must not update the map. Violations caused incidents for years. How should an organisation handle API contracts that cannot be checked by the compiler?

CopyOnWriteArrayList

ConceptFoundations6 min read
How does CopyOnWriteArrayList work and when is it a good choice?
ScenarioIntermediate7 min read
A service stores active WebSocket sessions in a CopyOnWriteArrayList. With 50,000 sessions connecting and disconnecting constantly, CPU and allocation rate are very high. Explain and propose a replacement.
ScenarioAdvanced6 min read
A fleet-wide CPU increase after a shared library release is traced to code that registers and unregisters a listener in a CopyOnWriteArrayList on every request. You lead the response across the affected teams. What do you do now and afterwards?

ConcurrentSkipListMap

ConceptFoundations6 min read
What is ConcurrentSkipListMap, how does it compare with a synchronized TreeMap, and what are its caveats?
CodingIntermediate7 min read
You keep a sliding five-minute window of events keyed by timestamp in a ConcurrentSkipListMap<Long, Event>, written by many threads. Show how to evict old events, and point out the bug in using epoch milliseconds as the key.
ConceptPrincipal6 min read
The JDK provides a concurrent sorted map built on a skip list (ConcurrentSkipListMap) rather than a concurrent balanced tree. Why, and what general lesson does it give about choosing data structures and system designs under concurrency?

ConcurrentLinkedQueue

ConceptFoundations6 min read
What kind of queue is ConcurrentLinkedQueue, and when would you choose LinkedBlockingQueue instead?
DebuggingIntermediate6 min read
A consumer thread runs
while (running) {
Task t = queue.poll();
if (t != null) t.run();
}
over a ConcurrentLinkedQueue. The service burns a full CPU core even when idle. Explain and fix.
LeadershipPrincipal7 min read
Some teams want to adopt specialised concurrent structures such as JCTools queues, Agrona or the LMAX Disruptor instead of JDK concurrent collections. Over a ten-year horizon, how would you decide, and what policy would you set?

Synchronized wrappers vs concurrent collections

CodingFoundations6 min read
Is this thread-safe?
Map<String, Integer> m = Collections.synchronizedMap(new HashMap<>());
if (!m.containsKey(k)) {
m.put(k, 1);
}
Also, how must you iterate m safely?
ConceptIntermediate6 min read
Compare Hashtable, Collections.synchronizedMap and ConcurrentHashMap for a shared map in a service under high concurrency. Is there any case where the synchronized wrapper is the better choice?
LeadershipAdvanced6 min read
Code reviews across your teams repeatedly find shared mutable HashMaps and ArrayLists in Spring singleton beans. What standard for shared mutable state would you set, and how would you make it stick?
ConceptPrincipal6 min read
Java went from synchronized Hashtable and Vector (1.0), to unsynchronized collections plus Collections.synchronized wrappers (1.2), to java.util.concurrent (5), to the lock-per-bin ConcurrentHashMap rewrite (8). What drove each change, and what lesson do you take for platform decisions in your organisation?