Why Debugging a Simple ConcurrentLinkedQueue Triggers a NullPointerException in IntelliJ IDEA
The article recounts a puzzling case where a minimal Java program using ConcurrentLinkedQueue runs fine normally but throws a NullPointerException when debugged in IntelliJ IDEA, explains the underlying cause involving the IDE's automatic toString invocation, and shows how to disable the offending settings.
While exploring the Java ConcurrentLinkedQueue (CLQ) source code, the author created a tiny demo that simply creates a CLQ instance and calls offer to insert an element. The program runs without issues when executed directly.
To better understand the internal structure, the author copied the JDK CLQ implementation into a custom class WhyCLQ and added a printWhyCLQ method that traverses the queue and prints each node:
public void printWhyCLQ() {
StringBuilder sb = new StringBuilder();
for (Node
p = first(); p != null; p = succ(p)) {
E item = p.item;
sb.append(item).append("->");
}
System.out.println("链表item对象指向 =" + sb);
}When the program is run normally, the printed chain matches the expected structure. However, when the same code is executed under the IntelliJ debugger, a NullPointerException occurs.
The root cause is that IntelliJ IDEA, by default, calls the object's toString method while evaluating variables in the debugger. The CLQ's toString implementation internally invokes the first() method, which updates the head node via updateHead(h, p) . This side‑effect changes the queue's internal state, making head.next null and leading to the exception.
By disabling the two debugger settings that automatically invoke toString , the program behaves identically in both normal and debug runs, confirming that the unexpected call was the culprit.
The article uses this incident to illustrate a broader lesson: methods like toString can contain hidden logic that interferes with debugging, so developers should keep such methods side‑effect‑free or be aware of IDE behaviors that may trigger them.
IT Services Circle
Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.
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.