java中ThreadLocal取不到值的兩種原因
阿新 • • 發佈:2020-11-18
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(),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取不到值內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!