ThreadLocals effect and side by side

Assuming

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

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

+4
source share
2 answers

Interest Ask. As Tom Hawtin - tackline explained, you basically create ThreadLocal<String>() instances. Now let's see how ThreadLocal actually stores values ​​(simplified):

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

It takes some kind of map attached to each thread, and sets the value using this (I) as the key. This means that if you have two ThreadLocals (created by different class loaders), they have a different this link, thereby effectively storing different values.

In general - you cannot, for example. use ThreadLocal as a workaround for local loaders of the loader class and create local threads.

+5
source

Classes loaded by different class loaders are different classes. Thus, it is actually 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>(); } 
+3
source

Source: https://habr.com/ru/post/1340050/


All Articles