6

Assuming

class A{
         private static final ThreadLocal<String> tl = new ThreadLocal<String>();
}

If A is loaded in just one classloader on the vm, the value of t1 is obvious. But what happens to t1 if A is loaded side-by-side in two different classloaders ? Will the value be shared for a given thread ?

Nick Bastin
  • 30,415
  • 7
  • 59
  • 78
krosenvold
  • 75,535
  • 32
  • 152
  • 208
  • Each classloader has it's OWN instance of the class, hence 2 instance of t1. So 2 different. You can experiment by removing static part from the thread local, i.e. every object can see a different value per thread. You can look at classes are just objects ensured to be singleton per classloader. – bestsss Feb 25 '11 at 22:44

2 Answers2

9

Interesting question. As Tom Hawtin - tackline explained, you are basically creating to instances of ThreadLocal<String>(). Now let's have a look at how ThreadLocal actually stores the values (simplified):

public void set(T value) {
    ThreadLocalMap map = getMap(Thread.currentThread());
    map.set(this, value);
}

It takes some sort of a map that is bound to every thread and sets the value using this (myself) as a key. This means that if you have two ThreadLocals (created by different class loaders), they have different this reference, thus effectively storing different values.

All in all - you cannot e.g. use ThreadLocal as a workaround to class-loader local singletons and creating thread-local ones.

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
4

Classes loaded by different class loaders are different classes. So it's effectively the same as having:

class A {
    private static final ThreadLocal<String> tl = new ThreadLocal<String>();
}

class B {
    private static final ThreadLocal<String> tl = new ThreadLocal<String>();
}
Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305