Wednesday, February 9, 2011

Inspecting thread local variables In Java example

I ran into an issue with some Thread Local Variables recently and came up with a quick way to actually see the buggers.

Using reflection you can get a good idea of the TLVs on your current thread.

package threadLocal;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class sandbox {

    public static void main(String[] args) throws Exception {

        Field field1 = Thread.class.getDeclaredField("threadLocals");
        field1.setAccessible(true);
        Object o1 = field1.get(Thread.currentThread());
        Field field2 = o1.getClass().getDeclaredField("table");
        field2.setAccessible(true);
        Object[] o2 = (Object[]) field2.get(o1);
        for (Object temp : o2) {
            if (temp != null) {
                Field field3 = temp.getClass().getDeclaredField("value");
                field3.setAccessible(true);
                Object o3 = field3.get(temp);
                System.out.println(o3);
            }
        }
    }
}
This will print out all the TLVs on your current thread. You can also set them to null or whatever you want with a little more reflection. Particularly by nulling out all the buckets in the Object[] o2.  Thread Local Variables are rarely used responsibly in Java programming. I advise you don't use them unless you really have a rock solid reason to (and even when you think you do, you probably don't). They are often forgotten about and lead to many unintended memory leaks down the line.

2 comments:

  1. This is really interesting , didn't know about this but I think IDE in debug mode can also this much of information, by the way thanks for showing an alternate way.

    Javin
    How to implement Thread in JAVA

    ReplyDelete
  2. That's probably true. Eclipse debug probably lets you dive into the thread. But it's nice to have a programmatic way to accomplish the same thing. runtime environments can act way differently then debug environments, especially when dealing with time sensitive actions such as an off box call.

    ReplyDelete