水一个
今天看书发现一个很有意思的设定,关于IDEA的。
先看问题是什么
import java.lang.reflect.Field;
import java.util.concurrent.ConcurrentLinkedQueue;
public class ConcurrentLinkedQueueTest {
public static void main(String[] args) {
ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<>();
print(queue);
queue.offer("item1");
print(queue);
queue.offer("item2");
print(queue);
queue.offer("item3");
print(queue);
}
private static void print(ConcurrentLinkedQueue queue) {
Field field = null;
boolean isAccessible = false;
try {
field = ConcurrentLinkedQueue.class.getDeclaredField("head");
isAccessible = field.isAccessible();
if (!isAccessible) {
field.setAccessible(true);
}
System.out.println("head: " + System.identityHashCode(field.get(queue)));
} catch (Exception e) {
e.printStackTrace();
} finally {
field.setAccessible(isAccessible);
}
}
}
结果就是,正常情况下,应该是四行输出一模一样的。
此处图片连续多次上传失败,就不展示了
但是在加了断点的调试下,输出与理论上不符。

为什么会这样?还记得在使用Debug模式运行时IntelliJ IDEA界面上显示的变量值吗?没错,为了显示这些变量的信息,Intelli]IDEA会调用对象的toString()方法 虽然在正常情况下不会有任何影响,但是在Debug模式下它可能会带来意想不到的结果。
当调用ConeurrentLinkedQueue 类的toString()方法时会获取队列的迭代器,而创建选代器时会调用队列的first方法,在first方法里会修改head的属性,从而导致输出的结果不一致。
为了不影响调试结果,需要关闭IntelliJ IDEA在Debug模式下的toString()特性预览 执行菜单File→-Settings→Build, Execution, DeploymentDebuggerData Views-Java命令打开数据预览窗口,如图5.30所示,它与图5.29所示的配置其实是相同的。
取消勾选Enable alternative view for Colle ctions classes和 Enable 'toString()'object view选项,保存后执行debug,结果就正常了。
此处图片连续多次上传失败,就不展示了
最后的配置是在这里

文章讨论了在使用IDEA进行Java程序调试时,由于调试模式下IDEA对集合类自动调用toString()方法,导致ConcurrentLinkedQueue在添加元素后的头部节点变化,从而影响输出结果。解决办法是关闭IDEA的特定调试设置,以避免对象视图的干扰,确保调试结果的准确性。
306

被折叠的 条评论
为什么被折叠?



