Two reasons why ThreadLocal cannot get a value

1. Two reasons

  • The first and most common one is that multiple threads use ThreadLocal
  • The second type is that different class loaders cause no value to be obtained. The essential reason is that different class loaders cause multiple ThreadLocal objects
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. Summary

  • The objects loaded by the two accumulators reference the same static variable ThreadLocal. In fact, ThreadLocal is not the same value, so the expected value cannot be obtained even in one thread.
  • Like dependency injection, if you create an object yourself, and then manually inject a dependency created by a container, assuming this dependency is created by a custom class adder, this may cause this situation.

Guess you like

Origin blog.csdn.net/TheThirdMoon/article/details/109624711