欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

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

时间:2021-07-24 09:36:07|栏目:JAVA代码|点击:

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并不是同一个值,所以即使在一个线程中也获取不到期望的值。

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

上一篇:在java中 利用匿名内部类进行较简洁的双括弧初始化的方法

栏    目:JAVA代码

下一篇:Java JDBC基本使用方法详解

本文标题:java中ThreadLocal取不到值的两种原因

本文地址:http://www.codeinn.net/misctech/161026.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有