Java - 如何在Eclipse中检查'ThreadLocal'变量的值?

时间:2010-11-22 14:59:58

标签: java eclipse debugging thread-local

我的网络应用中填充了几个ThreadLocal。而且,在远程调试webapp时,我希望在ThreadLocal中看到这些Eclipse变量的值(就像Eclipse在Debug透视图中的变量选项卡中显示其他变量一样)。

任何想法如何在ThreadLocal调试期间查看Eclipse变量的值?

谢谢!

3 个答案:

答案 0 :(得分:4)

在您的代码中,您必须将值放入局部变量中,您可以看到它。您应该能够断开使用ThreadLocal的位置。

问题是调试器的连接与你感兴趣的一个线程不同.Eclipse可以有一个解决方案,但我不知道它是什么。

答案 1 :(得分:2)

当您点击任何断点时,只需使用视图Expressions显示Thread.currentThread()的值,您就可以检查每个ThreadLocal值。

enter image description here

答案 2 :(得分:0)

如果您想了解更多详细信息,即希望查看以下所有代码的线程局部变量,可能会有所帮助:

    public static String printThreadLocal() {
        StringBuilder sb = new StringBuilder();
        try {
            Thread[] tarray = new Thread[Thread.activeCount()];
            Thread.enumerate(tarray);
            for (int i = 0; i < tarray.length; i++) {
                Field threadLocalField = Thread.class.getDeclaredField("threadLocals");
                threadLocalField.setAccessible(true);
                Object o1 = threadLocalField.get(tarray[i]); //Thread.currentThread());
                Field tableField = o1.getClass().getDeclaredField("table");
                tableField.setAccessible(true);
                Object[] o2 = (Object[]) tableField.get(o1);
                for (Object temp : o2) {
                    if (temp != null) {
                        Field valueField = temp.getClass().getDeclaredField("value");
                        valueField.setAccessible(true);
                        Object o3 = valueField.get(temp);
                        sb.append(o3.toString() + "\n");
                    }
                }
            }

        } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
            e.printStackTrace();
        }

        return sb.toString();
    }

您可以将MyClass.printThreadLocal()添加到Expressions