微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java中ThreadLocal取不到值的两种原因

这篇文章主要介绍了java中ThreadLocal取不到值的两种原因,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

1.两种原因

第一种,也是最常见的一种,就是多个线程使用ThreadLocal

第二种,类加载器不同造成取不到值,本质原因就是不同类加载器造成多个ThreadLocal对象

public class StaticclassLoaderTest { protected static final ThreadLocal local = new ThreadLocal(); //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并不是同一个值,所以即使在一个线程中也获取不到期望的值。

像依赖注入,如果你自己创建了一个对象,然后用手动注入了一个容器创建的依赖,假设这个依赖是自定义类加器创建的,可能会造成这种情况。

到此这篇关于java中ThreadLocal取不到值的两种原因的文章就介绍到这了,更多相关java ThreadLocal取不到值内容搜索编程之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程之家!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐