Java - How to check value of 'ThreadLocal' variables in Eclipse?

When you hit any breakpoint, just use view Expressions to display the value of Thread.currentThread() and you will be able to inspect every ThreadLocal value.

enter image description here


In your code you have to place the values into a local variable, which you can see. You should be able to breakpoint where the ThreadLocal is used.

The problem is that the debugger's connection is on a different thread to the one you are interested in. Eclipse could have a solution for this, but I don't know what it is.


If you want more details i.e. want to see the threadlocal variables for all the threads following code might help:

    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();
    }

You can add MyClass.printThreadLocal() to Expressions.