Why Does HashMap Trigger a CPU Spike? Uncovering the Red-Black Tree Loop Bug

The article investigates a CPU load spike caused by a red‑black tree cycle inside Java's HashMap after JDK 8, detailing monitoring steps, stack‑trace analysis, heap dump inspection, and concluding with a recommendation to replace HashMap with ConcurrentHashMap in concurrent scenarios.

Java Backend Technology
Java Backend Technology
Java Backend Technology
Why Does HashMap Trigger a CPU Spike? Uncovering the Red-Black Tree Loop Bug

After JDK 8 the HashMap resize dead‑loop was fixed, but a different issue can still cause a CPU load spike: a red‑black tree cycle that makes the map traversal endless.

When a machine showed a sudden load increase, I logged into the server, ran top, top -Hp, jstack and jmap, and saved the stack trace of the thread consuming the most CPU. cat stack | grep -i 34670 -C10 --color The stack trace pointed to the HashMap implementation. Although JDK 8 replaces the linked list with a tree during resize, I suspected a loop in the red‑black tree.

Opening the source, I found a for loop that could only become infinite if two TreeNode objects referenced each other as parents.

To verify, I dumped the heap with jhat and opened the generated HTML page (http://localhost:7000). I located the HashMap instance, inspected its table field and discovered a single TreeNode entry that had become a red‑black tree.

Further inspection of the parent field showed two nodes (0x72745d828 and 0x72745d7b8) whose parent references pointed to each other, forming a cycle.

This confirms that a red‑black tree can loop under certain concurrency scenarios, leading to the observed CPU spike.

Conclusion: avoid using HashMap in any concurrent context; prefer ConcurrentHashMap for safe and performant map operations.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

DebuggingJavaconcurrencyhashmapRed-Black TreeCPU Spike
Java Backend Technology
Written by

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!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.