Why Java’s ConcurrentHashMap Can Freeze Your CPU and How to Fix It
This article explains the hidden multithreading bugs in JDK 7 HashMap and JDK 8 ConcurrentHashMap that can cause 100% CPU usage, demonstrates how to reproduce them, and offers practical ways to avoid or resolve the issue.
In JDK 7 the HashMap implementation can enter an infinite loop during resize when accessed concurrently, leading to 100% CPU usage and even data loss.
Although HashMap is not thread‑safe, developers often unintentionally place it in multithreaded contexts; the usual remedy is to switch to ConcurrentHashMap, but JDK 8 introduced its own bug that also caused CPU spikes, which was fixed in JDK 9 (see bug ID JDK‑8062841).
Running the following sample program reproduces the JDK 8 ConcurrentHashMap bug: the process stays in a running state while one thread consumes nearly all CPU resources.
Using top -Hp [pid] reveals a thread with close to 100% CPU; jstack -l [pid] shows the offending thread (nid=0x7ab9, decimal 31417) stuck inside computeIfAbsent.
The core problem is the recursive use of computeIfAbsent, which can also be observed in a Fibonacci example that similarly drives CPU to 100%.
To avoid this issue, do not call computeIfAbsent recursively; alternatively, downgrade to a segmented‑lock implementation or upgrade to JDK 9 where the bug is resolved.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
