国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

java中ThreadLocal取不到值的兩種原因

瀏覽:3日期:2022-08-21 08:38:01

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取不到值內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Java
相關文章:
主站蜘蛛池模板: 仁布县| 二连浩特市| 广饶县| 晋城| 孟津县| 怀化市| 云林县| 平泉县| 呼玛县| 苗栗市| 崇左市| 孝义市| 宜昌市| 南皮县| 宁阳县| 子长县| 潢川县| 禹州市| 砚山县| 武邑县| 汉沽区| 即墨市| 武鸣县| 磐安县| 营口市| 长武县| 新河县| 乃东县| 区。| 亚东县| 漯河市| 晋宁县| 定日县| 右玉县| 丰顺县| 青神县| 民县| 邹平县| 莒南县| 新昌县| 通山县|