Workbench / Volume 3 Companion: The Backend
V3·35
Collections
Companion to Volume 3, chapter 35: how the four shapes, their implementations, ordering, iteration, immutability and concurrency connect; new angles (a heap as a hospital triage desk, a sorted set plus a map as a library's shelves and catalogue, fail-fast as a smoke alarm rather than a sprinkler); what the chapter simplifies, measured on JDK 21: a for-each removal that threw no exception and skipped an element, a LinkedHashMap whose order Map.copyOf scrambled differently on each of three runs, and a PriorityQueue removal 276 times slower than a TreeSet's; the theory behind the structures; how OpenJDK's ArrayList iterator, PriorityQueue.remove and List.copyOf actually work; four debugging drills; interview questions with how to approach each.
Understanding it better
Concept map
Chapter 35 has five parts: the shapes (list, set, map, queue, and choosing between implementations), how they work (dynamic arrays, hash tables and the equals/hashCode contract, trees, heaps, complexity and memory), ordering and iteration (Comparable, Comparator, iterators and fail-fast behaviour), immutability (copies and views) and sharing (concurrent collections, persistent collections in functional languages).
The links worth remembering:
- Choose by every operation, not the main one. A structure is right for a set of operations. The kitchen queue was a heap, right for "what's next" and wrong for "cancel this one", an operation added later (Stage 36).
- Every structure depends on a contract from its elements. Hash tables need consistent
equalsandhashCodeon unchanging fields; trees need a comparator that's total and consistent; heaps need the priority not to change while the element is inside. - Immutability is the cheapest concurrency and the cheapest safety. An unshared or unchanging collection needs no locks, no defensive copies by callers and no fail-fast checks.
Explain it differently
1. A heap is a triage desk. The nurse always knows who's most urgent, and the next arrival is quickly slotted in. Ask "is Mr Rao still waiting?" and she has to walk the whole waiting room: the desk is organised for "who's next", not "where is this person".
2. A sorted set plus a map is a library's shelves and catalogue. The shelves keep books in order (browse from the first); the catalogue says where each book is (find one directly). Move a book and both must change, or the catalogue lies.
3. A hash table is a cloakroom. Your ticket number (the hash) says which hook; the attendant checks the coat matches (equals). If you change your coat after handing it in (a mutable key), the attendant looks on the wrong hook.
4. Fail-fast is a smoke alarm, not a sprinkler. It often tells you something went wrong, and it isn't guaranteed to go off. When it stays quiet, the fire may still be burning (Gaps 1).
5. A view is a window; a copy is a photograph. unmodifiableList is a window onto a room someone else can rearrange; List.copyOf is a photo of the room as it was.
6. A persistent collection is a family tree of versions. Each change makes a new version that shares almost everything with the old one; nobody's version ever changes under them.
Gaps and misconceptions
What the chapter oversimplifies
All outputs are real, from OpenJDK 21.0.12 (exp/36 in the build), unless stated.
1. Fail-fast is best effort, and the common case can be silent. The chapter says a for-each removal throws ConcurrentModificationException. Removing each of three targets from [d1, d2, d3, d4] inside a for-each:
remove d2 inside for-each: ConcurrentModificationException
remove d3 inside for-each: no exception, list [d1, d2, d4]
remove d4 inside for-each: ConcurrentModificationException
Removing the second-to-last element threw nothing, and the loop ended without visiting d4. After the removal the size is 3 and the iterator's cursor is 3, so hasNext() is false and next(), where the check lives, is never called (Code walkthrough). Code that "removes the matching element and processes the rest" silently skips one. The Javadoc says it plainly: fail-fast behaviour "cannot be guaranteed". removeIf, or the iterator's own remove, is correct; catching the exception is not a strategy.
2. "Use an immutable copy" can change order. The chapter recommends Map.copyOf at boundaries. Copying a LinkedHashMap of request headers, three runs of the same program:
LinkedHashMap [host, accept, x-customer-id, idempotency-key, content-length, sec-fetch-site]
Map.copyOf [host, content-length, sec-fetch-site, x-customer-id, idempotency-key, accept]
Map.copyOf [x-customer-id, idempotency-key, accept, host, content-length, sec-fetch-site]
Map.copyOf [sec-fetch-site, x-customer-id, idempotency-key, accept, host, content-length]
Map.copyOf and Set.of deliberately randomise iteration per JVM run (a SALT chosen at startup) so that code can't come to depend on an order that was never promised; HashMap's order, by contrast, was the same on all three runs, which is how such dependencies get written. Where order is part of the contract (headers written in order, JSON fields, a golden master), copy into a LinkedHashMap and wrap it: Collections.unmodifiableMap(new LinkedHashMap<>(m)). Stage 36 did exactly this for TiffinBox's request and response records.
3. "A priority queue is O(log n)" holds for the head only. Cancelling 10% of the tickets from the middle of a queue:
n= 1,000 cancel 100: PriorityQueue.remove 0.05 ms TreeSet+HashMap 0.02 ms ratio 2x
n= 10,000 cancel 1,000: PriorityQueue.remove 3.21 ms TreeSet+HashMap 0.44 ms ratio 7x
n=100,000 cancel 10,000: PriorityQueue.remove 2,153.05 ms TreeSet+HashMap 7.79 ms ratio 276x
PriorityQueue.remove(Object) is a linear scan (indexOf) then a sift, so removing k of n is O(k·n): ten times the elements, about 100 to 700 times the time here (cache effects make it worse than linear per call at 100,000). A TreeSet ordered by (time, sequence) plus a HashMap from id to entry removes in O(log n). The timings are one machine's, after a warm-up round; the shape is the point. Note too what changing an element's priority while it's in a heap does: nothing re-sorts it, and the heap's order is silently wrong (Exercises P5's hint).
4. List.copyOf doesn't always copy.
view [d1, d2, d3] copy [d1, d2]
List.copyOf(copy) == copy: true List.copyOf(view) == view: false
List.copyOf with a null: NullPointerException
On a list that's already immutable it returns the same object (no copy, no cost), which is why copying in every record's compact constructor is cheap. On an unmodifiable view it copies, because the view can still change. And it rejects nulls, so a list that may contain them can't be copied this way.
Common misconceptions
| Misconception | What's actually true | Where it's shown |
|---|---|---|
| "Removing in a for-each always throws." | Removing the second-to-last element ends the loop silently, skipping the last. | Gaps 1 |
| "Immutable collections keep the order I put things in." | List.of does; Set.of and Map.copyOf randomise per run. |
Gaps 2 |
| "PriorityQueue operations are O(log n)." | Only at the head; remove(Object) and contains are O(n). |
Gaps 3 |
"unmodifiableList makes a list immutable." |
It's a read-only view of a list that can still change. | the chapter's lab |
"List.copyOf always allocates." |
Not for an already-immutable list. | Gaps 4 |
| "A TreeSet uses equals." | It uses the comparator: compare = 0 means duplicate. | Exercises P4 |
| "ConcurrentHashMap makes my code thread-safe." | Each call is atomic; get-then-put isn't. | Exercises P6 |
Theoretical gaps: the ideas behind the chapter
1. Amortised analysis. ArrayList.add is O(1) amortised: doubling (×1.5 in Java) means the total copying over n adds is O(n). Individual adds can take O(n); latency-sensitive code can pre-size.
2. Universal hashing and hash flooding. A hash table's O(1) assumes keys spread evenly. An attacker who knows the hash function can choose colliding keys; Java 8 turns long bucket chains into trees (O(log n) when keys are Comparable), and other languages randomise their hash functions per process (Python, Rust, Go).
3. Balanced search trees. TreeMap is a red-black tree: height at most 2·log₂(n+1), so every operation is O(log n). B-trees are the same idea with wide nodes, for disks and caches (Volume 6, databases).
4. Binary heaps. A complete binary tree stored in an array where each parent is at most its children. Building one from n elements is O(n), not O(n log n) (Floyd, 1964). Indexed heaps (keeping each element's position in a map) support decrease-key in O(log n), which Dijkstra's algorithm uses.
5. Persistent data structures. Okasaki's Purely Functional Data Structures (1998) and Bagwell's hash array mapped tries (2001), the basis of Clojure's and Scala's maps: updates copy only the path to the changed node, O(log₃₂ n).
Applying it
Code walkthrough
Three pieces of OpenJDK 21 (openjdk/jdk21u, src/java.base/share/classes/java/util/) explain Gaps 1, 3 and 4.
ArrayList's iterator: where fail-fast lives
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
The check is in next(), not hasNext(). Remove d3 after reading it: cursor is 3, size drops to 3, hasNext() returns false, and the loop ends without ever calling next() again (Gaps 1). Remove d2 instead: cursor 2, size 3, hasNext() true, next() sees modCount changed and throws. The iterator's own remove() resets cursor = lastRet and expectedModCount = modCount, which is why it's safe.
PriorityQueue.remove: a scan, then a sift
private int indexOf(Object o) {
if (o != null) {
final Object[] es = queue;
for (int i = 0, n = size; i < n; i++)
if (o.equals(es[i]))
return i;
}
return -1;
}
public boolean remove(Object o) {
int i = indexOf(o);
if (i == -1)
return false;
else {
removeAt(i);
return true;
}
}
E removeAt(int i) {
// assert i >= 0 && i < size;
final Object[] es = queue;
modCount++;
int s = --size;
if (s == i) // removed last element
es[i] = null;
else {
E moved = (E) es[s];
es[s] = null;
siftDown(i, moved);
if (es[i] == moved) {
siftUp(i, moved);
if (es[i] != moved)
return moved;
}
}
return null;
}
indexOf walks the array calling equals on each element: O(n), and the reason for Gaps 3. removeAt itself is O(log n): it moves the last element into the hole and sifts it down, or up if it's smaller than its new parent. Note that remove uses equals, so a record ticket is found by value.
List.copyOf: copy only when needed
static <E> List<E> listCopy(Collection<? extends E> coll) {
if (coll instanceof List12 || (coll instanceof ListN<?> c && !c.allowNulls)) {
return (List<E>)coll;
} else if (coll.isEmpty()) { // implicit nullcheck of coll
return List.of();
} else {
return (List<E>)List.of(coll.toArray());
}
}
List12 and ListN are the JDK's own immutable lists (List.of, stream().toList() uses a ListN that allows nulls, so it is copied). Anything else is copied through toArray() into List.of, which rejects nulls (Gaps 4). The same file starts with the salt that randomises Set.of and Map.copyOf order: SALT32L is computed from System.nanoTime() once per JVM, "so that iteration order will vary between JVM runs" (Gaps 2).
Debugging drills
D1. The cook makes a cancelled order
A restaurant's kitchen screen sometimes shows an order the customer cancelled ten minutes earlier. It never happens with one order at a time.
D2. A test that fails one run in six
After a refactor that "made the request record immutable", a test asserting the exact header lines of a proxied request fails intermittently, always with the same headers in a different order.
D3. An exception only when someone disconnects
The live kitchen feed keeps a List<Listener>; publish loops over it and calls each one. Under load, a ConcurrentModificationException appears whenever a client disconnects, and sometimes one listener misses an event without any exception.
D4. A sublist that breaks later
A pager keeps page = results.subList(20, 40) and renders it after a background refresh appends to results. Rendering throws ConcurrentModificationException, far from the code that changed anything.
Career-oriented
Interview prep
Mid-level 1: how a HashMap works
Question. "Explain what happens when you call put on a HashMap."
How to get there. Hash, bucket, collision, resize, and the contract.
Mid-level 2: removing while iterating
Question. "How do you remove items from a list while looping over it, and why doesn't the obvious way work?"
How to get there. The modification count, then the safe ways.
Senior 1: a queue you can change
Question. "Design a priority queue of jobs where jobs can be cancelled or rescheduled while queued."
How to get there. List the operations and their required costs, then pick structures that meet all of them.
Senior 2: a memory-bound lookup
Question. "A service holds 20 million Map<Long, Integer> entries and runs out of heap. What do you do?"
How to get there. Measure the cost per entry, then remove the overhead.
Staff 1: a derived structure that diverged
Question. "In production, an in-memory index disagreed with the database for weeks before anyone noticed. How do you stop this class of bug?"
How to get there. Single update path, rebuildability, detection.
Staff 2: from one server to many
Question. "Our kitchen queue lives in one server's memory. We need three servers. What changes?"
How to get there. Where the state goes, how updates stay ordered, what the failure modes are.