java中ThreadLocal取不到值的两种原因
#代码知识 发布时间: 2026-01-12
1.两种原因

第一种,也是最常见的一种,就是多个线程使用ThreadLocal
第二种,类加载器不同造成取不到值,本质原因就是不同类加载器造成多个ThreadLocal对象
public class StaticClassLoaderTest {
protected static final ThreadLocal<Object> local = new ThreadLocal<Object>();
//cusLoader加载器加载的对象
private Test3 test3;
public StaticClassLoaderTest() {
try {
test3 = (Test3) Class.forName("gittest.Test3", true, new cusLoader()).newInstance();
}
catch (Exception e) {
e.printStackTrace();
}
}
public Test3 getTest3() {
return test3;
}
public static void main(String[] args) {
try {
//默认类加载器加载StaticClassLoaderTest,并设置值
StaticClassLoaderTest.local.set(new Object());
new StaticClassLoaderTest().getTest3();
}
catch (Exception e) {
e.printStackTrace();
}
}
//自定义类加载器
public static class cusLoader extends ClassLoader {
@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
if (name.contains("StaticClassLoaderTest")) {
InputStream is = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(name.replace(".", "/") + ".class");
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
IOUtils.copy(is, output);
return defineClass(output.toByteArray(), 0, output.toByteArray().length);
}
catch (IOException e) {
e.printStackTrace();
}
}
return super.loadClass(name, resolve);
}
}
}
public class Test3 {
public void test() {
//由cusLoader加载器加载StaticClassLoaderTest,并获取值,由于StaticClassLoaderTest并不相同所以无法获取到值
System.out.println(StaticClassLoaderTest.local.get());
}
}
2.总结
2个累加器加载的对象引用了相同的静态变量ThreadLocal,实际上ThreadLocal并不是同一个值,所以即使在一个线程中也获取不到期望的值。
像依赖注入,如果你自己创建了一个对象,然后用手动注入了一个容器创建的依赖,假设这个依赖是自定义类加器创建的,可能会造成这种情况。
上一篇 : 快速解决vue2+vue-cli3项目ie兼容的问题
下一篇 : Spring 依赖注入实现示例
-
SEO外包最佳选择国内专业的白帽SEO机构,熟知搜索算法,各行业企业站优化策略!
SEO公司
-
可定制SEO优化套餐基于整站优化与品牌搜索展现,定制个性化营销推广方案!
SEO套餐
-
SEO入门教程多年积累SEO实战案例,从新手到专家,从入门到精通,海量的SEO学习资料!
SEO教程
-
SEO项目资源高质量SEO项目资源,稀缺性外链,优质文案代写,老域名提权,云主机相关配置折扣!
SEO资源
-
SEO快速建站快速搭建符合搜索引擎友好的企业网站,协助备案,域名选择,服务器配置等相关服务!
SEO建站
-
快速搜索引擎优化建议没有任何SEO机构,可以承诺搜索引擎排名的具体位置,如果有,那么请您多注意!专业的SEO机构,一般情况下只能确保目标关键词进入到首页或者前几页,如果您有相关问题,欢迎咨询!