温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java项目中ThreadLocal无法取值的原因有哪些

发布时间:2020-11-18 14:52:19 来源:亿速云 阅读:516 作者:Leah 栏目:开发技术

今天就跟大家聊聊有关java项目中ThreadLocal无法取值的原因有哪些,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

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<&#63;> 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无法取值的原因有哪些有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI