ThreadLocals 和并行类加载的效果
假设
class A{
private static final ThreadLocal<String> tl = new ThreadLocal<String>();
}
如果 A 仅在 vm 上的一个类加载器中加载,则 t1 的值是显而易见的。但是如果 A 在两个不同的类加载器中并排加载,t1 会发生什么情况?该值会被给定线程共享吗?
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有趣的问题。正如 Tom Hawtin -tackline 所解释的那样,您基本上是在创建 ThreadLocal() 的实例。现在让我们看一下
ThreadLocal
实际上如何存储值(简化):它需要某种绑定到每个线程的映射,并使用
this
设置值(我自己)作为钥匙。这意味着,如果您有两个 ThreadLocals(由不同的类加载器创建),它们将具有不同的 this 引用,从而有效地存储不同的值。总而言之,您不能使用 ThreadLocal 作为类加载器本地单例和创建线程本地单例的解决方法。
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.不同的类加载器加载的类是不同的类。所以它实际上等同于:
Classes loaded by different class loaders are different classes. So it's effectively the same as having: