Why LinkedBlockingQueue’s dequeue sets h.next = h – The hidden GC trick explained
This article deep‑dives into the LinkedBlockingQueue.dequeue implementation, revealing why the line h.next = h is essential for helping the garbage collector, how cross‑generation references affect GC performance, and the role of weakly‑consistent iterators in Java's concurrent queue.
What does it do?
The method java.util.concurrent.LinkedBlockingQueue#dequeue removes the head node of the queue and returns its item, doing nothing else.
Running a demo shows the linked list before and after removal, illustrating that the head node (node 1) disappears after the operation.
help GC?
Investigation of JDK bug reports (JDK‑6805775, JDK‑6806875) shows that the line h.next = h was added to break cross‑generation references, preventing the head node from lingering in the old generation and causing excessive Full GC cycles.
Benchmarks comparing JDK 6 (without h.next = h) and JDK 8 (with the line) demonstrate a dramatic reduction in Full GC events when the line is present.
When the queue resides in the old generation and its nodes are in the young generation, removing a node without clearing its next reference creates a cross‑generation reference that hinders Young GC, forcing a Full GC to reclaim the node.
h.next=null ???
Both h.next = h and h.next = null can break the reference, but the JDK implementation chose h.next = h because it aligns with the iterator’s handling of dequeued nodes, where a dequeued node is marked by p.next == p.
The weakly‑consistent iterator relies on this self‑linking to correctly advance when a node has been removed concurrently, ensuring that iteration continues with the next reachable node.
Thus, setting h.next = h both aids the garbage collector and supports the iterator’s contract.
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.
Su San Talks Tech
Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.
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.
