Quick revision
The short answer
Both symptoms come from the same bug: a plain HashMap shared and updated by many threads. On Java 7, two threads resizing at once could link nodes into a cycle, because transfer() inserted entries at the head of each new bucket, and any get() on that bucket then looped forever at 100% CPU. Java 8 changed transfer to keep node order, so that cycle no longer forms, but HashMap is still not thread-safe: concurrent puts overwrite each other, entries are lost during resizes and size goes wrong, and concurrent treeification can still corrupt tree bins. The fix is ConcurrentHashMap or proper synchronization, not the JDK upgrade.
What to remember
In this answer, we saw that both incidents come from one cause: a static HashMap updated by many threads. On Java 7, racing resizes used head insertion in transfer(), which could link nodes into a cycle and make get() loop forever at full CPU. Java 8 preserves node order during resize, so that cycle no longer forms, but HashMap is still not thread-safe: concurrent puts overwrite each other, entries are lost during resizes, size becomes inconsistent, and concurrent treeification can still corrupt tree bins. The real fix is ConcurrentHashMap, immutable publication or proper synchronization, not the JDK upgrade.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Both symptoms come from the same bug: a plain HashMap shared and updated by many threads. On Java 7, two threads resizing at once could link nodes into a cycle, because transfer() inserted entries at the head of each new bucket, and any get() on that bucket then looped forever at 100% CPU. Java 8 changed transfer to keep node order, so that cycle no longer forms, but HashMap is still not thread-safe: concurrent puts overwrite each other, entries are lost during resizes and size goes wrong, and concurrent treeification can still corrupt tree bins. The fix is ConcurrentHashMap or proper synchronization, not the JDK upgrade.
Why this question is asked
This is a classic case of an upgrade that seemed to fix a bug but only changed its symptom. The CPU incidents were dramatic and easy to notice; the missing entries are quiet and arguably worse, because they corrupt data without an alarm. Interviewers like it because explaining both symptoms requires knowing how HashMap resizes in each version and what thread-safety really means. In this answer, we will recap why HashMap is not thread-safe, walk through how Java 7 built a cycle, see why Java 8 stopped the loop but not the corruption, and then fix the service and find similar maps.
1A Quick Recap: What Thread-Safe Means Here
A class is thread-safe if it behaves correctly when several threads use it at the same time without extra coordination. HashMap's Javadoc states clearly that it is not: if multiple threads access it concurrently and at least one modifies it structurally, access must be synchronized externally.
The reason is that a put() is many separate steps: read the bucket, compare keys, link a new node, increment the size, maybe resize. With no lock, two threads can interleave those steps in any order, and each one can see the other's work half done. Java's memory model also allows a thread to see stale values of fields written by another thread unless there is a happens-before relationship, such as a lock or a volatile write, between them.
2How Java 7 Built a Cycle
Java 7's resize called transfer(), which walked each old bucket and moved every entry to the head of its new bucket.
6 messages in order. Play them, or step through them one at a time.
After this, any get() that reaches this bucket and does not find its key walks the cycle forever.
Head insertion reverses the order of a chain: a bucket holding A -> B in the old table holds B -> A in the new one, if both land in the same bucket. Now suppose two threads both see that the map needs to grow and both run transfer() on the same nodes.
Thread 1 reads e = A and next = B at step (1), and is then paused by the scheduler. Thread 2 runs the whole transfer, so in its new table B.next is now A. Thread 1 resumes. It puts A at the head of its own new bucket, then moves to B. It reads B.next, which thread 2 changed to A, so its next is A again. It puts B at the head, pointing to A. Then it processes A once more and sets A.next = B. Now A points to B and B points to A: a cycle.
3Why the Threads Spun for Minutes
Once the cycle exists, a get() for a key that hashes to that bucket and is not A or B follows next pointers forever, because it never reaches null. The thread does not block, it runs, so CPU goes to 100%. Each request that touches that bucket adds another spinning thread, and the thread dumps show them all in HashMap.get(), exactly as in the incident. Restarting the service clears it until the next unlucky concurrent resize.
4What Java 8 Changed, and What It Did Not
Java 8 rewrote resize(). It splits each bucket into a lo list and a hi list and appends nodes at the tail, so order is preserved and there is no reversal. That removes the specific interleaving that produced the cycle, which is why the CPU spikes stopped after the upgrade.
But nothing about Java 8's HashMap is designed for concurrent writers. Two threads putting different keys into an empty bucket can both read null, both create a node and both write the bucket; the second write wins and the first entry is silently lost. A thread that puts into the old table after another thread has already copied that bucket to the new table writes into an array nobody reads any more. ++size is not atomic, so the size drifts from the real count, which also makes resizes happen at the wrong time. And reader threads can see a half-moved table and get null for keys that are present.
| JDK | What concurrent writes can do | Symptom |
|---|---|---|
| Java 7 | head insertion during racing resizes creates a cycle | threads stuck in get(), 100% CPU |
| Java 8+ | lost puts, lost moves during resize, wrong size | missing entries, no error |
| Java 8+ | racing treeify or rebalance corrupts a tree bin | rare spins in TreeNode methods |
| Any | ConcurrentHashMap or a lock | correct |
Notice that usually nothing throws and nothing hangs (an occasional ClassCastException from a half-converted tree bin is another known symptom). The map simply holds fewer entries than were put, which is the missing-entries report from customers. Tree bins add another risk: if two threads treeify or rebalance the same bin at once, the red-black tree's parent and child links can be corrupted, and there have been reports of threads spinning inside TreeNode methods such as root() or balanceInsertion on Java 8 and later. So an infinite loop is still possible, just rarer and in a different place.
5The Fix
The fix is to stop sharing a mutable HashMap without coordination. For a map that many threads read and write, ConcurrentHashMap is the standard choice: it locks individual bins for writes, reads without locking, resizes cooperatively across threads, and offers atomic compound operations such as computeIfAbsent and merge. For reference data that is loaded once and refreshed occasionally, a simpler and faster pattern is to build a new map privately, wrap it with Map.copyOf, and publish it through a volatile field or an AtomicReference, so readers always see a complete, immutable map.
Collections.synchronizedMap also works, but it serializes every access behind one lock, so it is usually a fallback rather than the first choice. Note that ConcurrentHashMap rejects null keys and values, so code that stored nulls needs a small change.
6Follow-up questions
How would you find every shared mutable HashMap in a large codebase?
I would combine a few methods. A search for static fields and singleton-bean fields of type Map, HashMap or HashSet that are not final immutable collections finds the obvious ones, and Spring singletons with map fields mutated in request-handling methods are a common hiding place. Static analysis helps: SpotBugs has multithreaded correctness detectors, and annotations such as @GuardedBy let Error Prone check locking, though rule coverage varies by tool version. In a running system, a heap dump analysed with Eclipse MAT can list HashMap instances reachable from static fields or long-lived beans. And a concurrency stress test, or jcstress for a critical class, confirms the suspects.
Why did the Java 7 loop only happen occasionally?
It needed two threads to resize the same map at the same moment, with a pause at exactly the wrong step, and then a later get() for a missing key in the affected bucket. Resizes are rare once a map has grown, so the window was small, but under load it eventually opened.
Is a HashMap safe if only one thread writes and others only read?
No, not without a happens-before relationship. Readers can see a partially resized table or stale fields and return wrong results. Safe options are building the map fully and publishing it immutably, or using ConcurrentHashMap.
7Conclusion
In this answer, we saw that both incidents come from one cause: a static HashMap updated by many threads. On Java 7, racing resizes used head insertion in transfer(), which could link nodes into a cycle and make get() loop forever at full CPU. Java 8 preserves node order during resize, so that cycle no longer forms, but HashMap is still not thread-safe: concurrent puts overwrite each other, entries are lost during resizes, size becomes inconsistent, and concurrent treeification can still corrupt tree bins. The real fix is ConcurrentHashMap, immutable publication or proper synchronization, not the JDK upgrade.
Open with
Both symptoms come from the same bug: a static HashMap written by many threads, which HashMap's documentation says is not allowed without external synchronization. On Java 7, resize called transfer, which moved each entry to the head of its new bucket, reversing the chain.
Then, if they want more
If two threads resized at once and one was paused after reading e and e.next, the other could reverse the chain underneath it, and when the first thread continued it linked the nodes into a cycle, A pointing to B and B pointing back to A.
Any get for a missing key in that bucket then followed next pointers forever, which is why threads were stuck in HashMap.get at 100 percent CPU. Java 8 rewrote resize to split each bucket into lo and hi lists with tail insertion, preserving order, so that particular cycle cannot form, and the CPU spikes went away.
But the map is still not thread-safe. Two threads can both see an empty bucket and the second write wins, so a put is lost; a thread can write to the old table after its bucket was moved; size is updated without atomicity; and concurrent treeification can corrupt tree bins, which has caused rare spins in TreeNode methods.
That is the missing data customers see. The upgrade only changed the symptom. I would replace the map with a ConcurrentHashMap, or, if it is reference data, build it privately and publish an immutable copy through a volatile field, and then search the codebase for other shared mutable maps.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 8, Java 7
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- java.util.HashMap, API documentation, The Collections Framework, overview
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "An old service on Java 7 has occasional incidents where CPU goes to 100% and thread...": https://scrivio-interview-library.netlify.app/java/hashmap-internals/39a62e772a/