问题描述
假设
class A{
private static final ThreadLocal<String> tl = new ThreadLocal<String>();
}
如果A仅在vm的一个类加载器中加载,则t1的值很明显。但是,如果将A并排加载到两个不同的类加载器中,那么t1会怎样?
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 ?
推荐答案
有趣的问题。正如 Tom Hawtin-大头钉所解释的,您基本上是在创建 ThreadLocal< String>()
的实例。现在让我们看一下 ThreadLocal
如何实际存储值(简化):
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);
}
它需要某种映射,该映射绑定到每个线程并设置使用 this
(我自己)作为键的值。这意味着,如果您有两个 ThreadLocals
(由不同的类加载器创建),则它们具有不同的 this
引用,因此有效存储不同的值。
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.
全部-您不能例如使用 ThreadLocal
作为类加载器本地单例并创建线程本地单例的解决方法。
All in all - you cannot e.g. use ThreadLocal
as a workaround to class-loader local singletons and creating thread-local ones.
这篇关于ThreadLocals和并行类加载的影响的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!