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 ?
Classes loaded by different class loaders are different classes. So it's effectively the same as having:
Interesting question. As Tom Hawtin - tackline explained, you are basically creating to instances of
ThreadLocal<String>()
. Now let's have a look at howThreadLocal
actually stores the values (simplified):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 twoThreadLocals
(created by different class loaders), they have differentthis
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.