欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-09-05 12:39:01
1.两种原因第一种,也是最常见的一种,就是多个线程使用threadlocal第二种,类加载器不同造成取不到值,本质原因就是不同类加载器造成多个threadlocal对象public class sta...

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中threadlocal取不到值的两种原因的文章就介绍到这了,更多相关java threadlocal取不到值内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!