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);
    }
  }

}                
当前标题:java项目中ThreadLocal无法取值的原因有哪些-创新互联
URL分享:http://ybzwz.com/article/pjsce.html