Java - How to check value of 'ThreadLocal' variables in Eclipse?
-
27-09-2019 - |
Question
I have couple of ThreadLocal
s populated in my web app. And, while remote debugging the webapp, I want to see the value of these ThreadLocal
variables in Eclipse
(just like the way Eclipse
shows other variables in the variables tab in Debug perspective).
Any idea how can I view the value of ThreadLocal
variables during debugging in Eclipse
?
Thanks!
Solution
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.
OTHER TIPS
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
.