{"id":233086,"date":"2022-01-05T08:26:48","date_gmt":"2022-01-05T00:26:48","guid":{"rendered":"https:\/\/lrxjmw.cn\/?p=233086"},"modified":"2021-12-27T19:27:44","modified_gmt":"2021-12-27T11:27:44","slug":"threadlocal-use-principle","status":"publish","type":"post","link":"https:\/\/lrxjmw.cn\/threadlocal-use-principle.html","title":{"rendered":"ThreadLocal\u7684\u6b63\u786e\u4f7f\u7528\u4e0e\u539f\u7406"},"content":{"rendered":"
ThreadLocal\u662f\u4ec0\u4e48<\/strong><\/div>\n

ThreadLocal\u662f\u7ebf\u7a0bThread\u4e2d\u5c5e\u6027threadLocals\u5373ThreadLocal.ThreadLocalMap\u7684\u7ba1\u7406\u8005\uff0cThreadLocal\u7528\u4e8e\u7ed9\u6bcf\u4e2a\u7ebf\u7a0b\u64cd\u4f5c\u81ea\u5df1\u7ebf\u7a0b\u7684\u672c\u5730\u53d8\u91cf\uff0c\u901a\u8fc7\u7ebf\u7a0b\u79c1\u6709\u4ece\u800c\u4fdd\u8bc1\u7ebf\u7a0b\u5b89\u5168\u6027\u3002<\/p>\n

ThreadLocal\u539f\u7406<\/strong><\/div>\n

\u62ffget()\u65b9\u6cd5\u6765\u8bf4\uff0c\u7ebf\u7a0b\u7684\u672c\u5730\u53d8\u91cf\u662f\u5b58\u653e\u5728\u7ebf\u7a0b\u5b9e\u4f8b\u7684\u5c5e\u6027ThreadLocalMap\u4e0a\u7684\uff0cThreadLocalMap\u672c\u8d28\u4e0a\u5c31\u662f\u4e00\u4e2aHashMap\uff0cThreadLocal\u53ea\u662f\u4e00\u4e2a\u7ba1\u7406\u8005\uff0c\u5f53\u6211\u4eec\u7684\u7ebf\u7a0b\u9700\u8981\u62ff\u5230\u81ea\u5df1\u7684\u672c\u5730\u53d8\u91cf\u65f6\uff0c\u6211\u4eec\u76f4\u63a5\u8c03\u7528ThreadLocal\u53bbget\u672c\u5730\u53d8\u91cf\u5373\u53ef\u3002
\n\u56e0\u4e3aget()\u65b9\u6cd5\u5e95\u5c42\u4f1a\u5148\u83b7\u53d6\u5230\u5f53\u524d\u7ebf\u7a0b\uff0c\u7136\u540e\u901a\u8fc7\u5f53\u524d\u7ebf\u7a0b\u62ff\u5230\u4ed6\u7684\u5c5e\u6027\u503cThreadLocalMap\uff0c\u5982\u679cThreadLocalMap\u4e3a\u7a7a\uff0c\u5219\u4f1a\u8c03\u7528ThreadLocal\u7684\u521d\u59cb\u5316\u65b9\u6cd5\u62ff\u5230\u521d\u59cb\u503c\u8fd4\u56de\uff0c\u5982\u679c\u4e0d\u4e3a\u7a7a\uff0c\u5219\u4f1a\u62ff\u8be5ThreadLocal\u4f5c\u4e3akey\u53bb\u83b7\u53d6\u8be5\u7ebf\u7a0b\u4e0b\u7684ThreadLocalMap\u91cc\u5bf9\u5e94\u7684value\u503c\u3002<\/p>\n

ThreadLocal\u5185\u5b58\u6cc4\u6f0f\u95ee\u9898<\/strong><\/div>\n

\u7ebf\u7a0b\u7684\u5c5e\u6027\u503cThreadLocalMap\u4e2d\u4f7f\u7528\u7684 key \u4e3a ThreadLocal \u7684\u5f31\u5f15\u7528,\u800cvalue\u662f\u5f3a\u5f15\u7528\u3002\u6240\u4ee5\uff0c\u5982\u679cThreadLocal\u6ca1\u6709\u88ab\u5916\u90e8\u5f3a\u5f15\u7528\u7684\u60c5\u51b5\u4e0b\uff0c\u5728\u5783\u573e\u56de\u6536\u7684\u65f6\u5019\uff0ckey \u4f1a\u88ab\u6e05\u7406\u6389\uff0c\u800cvalue \u4e0d\u4f1a\u88ab\u6e05\u7406\u6389\u3002\u8fd9\u6837\u7684\u8bdd\uff0cThreadLocalMap \u4e2d\u5c31\u4f1a\u51fa\u73b0 key \u4e3a null \u7684 Entry\u3002\u5047\u5982\u6211\u4eec\u4e0d\u505a\u4efb\u4f55\u63aa\u65bd\u7684\u8bdd\uff0cvalue \u6c38\u8fdc\u65e0\u6cd5\u88ab GC \u56de\u6536\uff0c\u8fd9\u4e2a\u65f6\u5019\u5c31\u53ef\u80fd\u4f1a\u4ea7\u751f\u5185\u5b58\u6cc4\u9732\u3002
\n\u56e0\u6b64\u9488\u5bf9\u8fd9\u79cd\u60c5\u51b5\uff0c\u6211\u4eec\u6709\u4e24\u79cd\u539f\u5219\uff1a
\nThreadLocal\u7533\u660e\u4e3aprivate static final\u3002JDK\u5efa\u8baeThreadLocal\u5b9a\u4e49\u4e3aprivate static\uff0c\u8fd9\u6837ThreadLocal\u7684\u5f31\u5f15\u7528\u95ee\u9898\u5219\u4e0d\u5b58\u5728\u4e86\u3002private\u4e0efinal \u5c3d\u53ef\u80fd\u4e0d\u8ba9\u4ed6\u4eba\u4fee\u6539\u53d8\u66f4\u5f15\u7528\u3002static \u8868\u793a\u4e3a\u7c7b\u5c5e\u6027\uff0c\u53ea\u6709\u5728\u7a0b\u5e8f\u7ed3\u675f\u624d\u4f1a\u88ab\u56de\u6536\u3002ThreadLocal\u4f7f\u7528\u540e\u52a1\u5fc5\u8c03\u7528remove\u65b9\u6cd5\u3002
\n\u6700\u7b80\u5355\u6709\u6548\u7684\u65b9\u6cd5\u662f\u4f7f\u7528\u540e\u5c06\u5176\u79fb\u9664\u3002<\/p>\n

\u5173\u4e8eInheritableThreadLocal<\/strong><\/div>\n

InheritableThreadLocal\u7c7b\u662fThreadLocal\u7c7b\u7684\u5b50\u7c7b\u3002ThreadLocal\u4e2d\u6bcf\u4e2a\u7ebf\u7a0b\u62e5\u6709\u5b83\u81ea\u5df1\u7684\u503c\uff0c\u4e0eThreadLocal\u4e0d\u540c\u7684\u662f\uff0cInheritableThreadLocal\u5141\u8bb8\u4e00\u4e2a\u7ebf\u7a0b\u4ee5\u53ca\u8be5\u7ebf\u7a0b\u521b\u5efa\u7684\u6240\u6709\u5b50\u7ebf\u7a0b\u90fd\u53ef\u4ee5\u8bbf\u95ee\u5b83\u4fdd\u5b58\u7684\u503c\u3002<\/p>\n

ThreadLocal\u4f7f\u7528<\/p>\n

\r\npublic class ThreadLocalTest {\r\n\r\n    \/\/\u7b2c\u4e00\u79cd\u521d\u59cb\u5316\u65b9\u5f0f\r\n    \/**\r\n     * \u58f0\u660e\u4e3astatic\u662f\u8ba9ThreadLocal\u5b9e\u4f8b\u968f\u7740\u7a0b\u5e8f\u7684\u7ed3\u675f\u624d\u7ed3\u675f\uff0c\u8fd9\u6837\u624d\u4e0d\u4f1a\u8ba9GC\u56de\u6536\u4e86\r\n     * \u58f0\u660e\u4e3afinal\u662f\u8ba9ThreadLocal\u5b9e\u4f8b\u5f15\u7528\u4e0d\u4f1a\u88ab\u66ff\u6362\uff0c\u8fd9\u6837\u5b50\u4e5f\u4e0d\u4f1a\u56e0\u4e3a\u88ab\u66ff\u6362\u5bfc\u81f4\u88abGC\u56de\u6536\r\n     * \u8fd9\u4e24\u4e2a\u58f0\u660e\u90fd\u662f\u4e3a\u4e86\u907f\u514d\u4f5c\u4e3akey\u7684ThreadLocal\u5bf9\u8c61\u6ca1\u6709\u5916\u90e8\u5f3a\u5f15\u7528\u800c\u5bfc\u81f4\u88abGC\u56de\u6536\uff0c\u4ece\u800c\u5bfc\u81f4\u5185\u5b58\u6cc4\u6f0f\u7684\u95ee\u9898\uff0c\u56e0\u4e3aThreadLocalMap\u4e2d\u7684ThreadLocal\r\n     * \u5bf9\u8c61\u4f5c\u4e3akey\u662f\u5f31\u5f15\u7528\uff0c\u4f1a\u88abGC\u56de\u6536\u3002\r\n     *\/\r\n    private static final ThreadLocal threadLocalStr = ThreadLocal.withInitial(() -> \"fresh\");\r\n\r\n    private static AtomicInteger intGen = new AtomicInteger(0);\r\n    \/\/\u7b2c\u4e8c\u79cd\u521d\u59cb\u5316\u65b9\u5f0f\r\n    private static final ThreadLocal threadLocalInt = new ThreadLocal<\/integer>() {\r\n        @Override\r\n        public Integer initialValue() {\r\n            return intGen.incrementAndGet();\r\n        }\r\n    };\r\n\r\n    public static void main(String[] args) throws InterruptedException {\r\n        ArrayList threads = new ArrayList<>();\r\n        for (int i = 0; i < 2; i++) {\r\n            Thread t = new Thread(() -> {\r\n                try {\r\n                    System.out.println(Thread.currentThread().getName() + \"   \" + threadLocalInt.get());\r\n                    System.out.println(Thread.currentThread().getName() + \"   \" + threadLocalStr.get());\r\n                    TimeUnit.SECONDS.sleep(5);\r\n                    threadLocalStr.set(\"bojack horseman\" + threadLocalInt.get());\r\n                    System.out.println(Thread.currentThread().getName() + \"   \" + threadLocalInt.get());\r\n                    System.out.println(Thread.currentThread().getName() + \"   \" + threadLocalStr.get());\r\n                } catch (InterruptedException e) {\r\n                    e.printStackTrace();\r\n                } finally {\r\n                    threadLocalInt.remove();\r\n                    threadLocalStr.remove();\r\n                }\r\n            });\r\n            t.start();\r\n            threads.add(t);\r\n        }\r\n        TimeUnit.SECONDS.sleep(2);\r\n        System.out.println(threads);\r\n        System.out.println(threadLocalStr);\r\n        System.out.println(threadLocalInt);\r\n    }\r\n    \/**\r\n     * Thread-0   1\r\n     * Thread-1   2\r\n     * Thread-0   fresh\r\n     * Thread-1   fresh\r\n     * [Thread[Thread-0,5,main], Thread[Thread-1,5,main]]\r\n     * java.lang.ThreadLocal$SuppliedThreadLocal@1ef7fe8e\r\n     * cn.vv.schedule.test.ThreadLocalTest$1@6f79caec\r\n     * Thread-1   2\r\n     * Thread-1   bojack horseman2\r\n     * Thread-0   1\r\n     * Thread-0   bojack horseman1\r\n     *\/\r\n\r\n}\r\n<\/thread><\/integer><\/string><\/pre>\n

InheritableThreadLocal\u4f7f\u7528<\/p>\n

\r\npublic class InheritableThreadLocalTest {\r\n\r\n    \/\/\u7b2c\u4e00\u79cd\u521d\u59cb\u5316\u65b9\u5f0f\r\n    private static final InheritableThreadLocal threadLocalStr = new InheritableThreadLocal<\/string>() {\r\n        @Override\r\n        public String initialValue() {\r\n            return \"fresh\";\r\n        }\r\n    };\r\n    private static AtomicInteger intGen = new AtomicInteger(0);\r\n    \/\/\u7b2c\u4e8c\u79cd\u521d\u59cb\u5316\u65b9\u5f0f\r\n    private static final ThreadLocal threadLocalInt = new ThreadLocal<\/integer>() {\r\n        @Override\r\n        public Integer initialValue() {\r\n            return intGen.incrementAndGet();\r\n        }\r\n    };\r\n\r\n    public static void main(String[] args) throws InterruptedException {\r\n        \/\/\u5982\u679c\u662fInheritableThreadLocal\uff0c\u5219\u7236\u7ebf\u7a0b\u521b\u5efa\u7684\u6240\u6709\u5b50\u7ebf\u7a0b\u90fd\u4f1a\u590d\u5236\u4e00\u4efd\u7236\u7ebf\u7a0b\u7684\u7ebf\u7a0b\u53d8\u91cf\uff0c\u800c\u4e0d\u662f\u53bb\u521d\u59cb\u5316\u4e00\u4efd\u7ebf\u7a0b\u53d8\u91cf\r\n        threadLocalStr.set(\"main\");\r\n        ArrayList threads = new ArrayList<>();\r\n        for (int i = 0; i < 2; i++) {\r\n            Thread t = new Thread(() -> {\r\n                try {\r\n                    System.out.println(Thread.currentThread().getName() + \"   \" + threadLocalInt.get());\r\n                    System.out.println(Thread.currentThread().getName() + \"   \" + threadLocalStr.get());\r\n                    TimeUnit.SECONDS.sleep(5);\r\n                    \/\/\u5b50\u7ebf\u7a0b\u53ef\u4ee5\u81ea\u7531\u5730\u6539\u53d8\u81ea\u5df1\u7684\u672c\u5730\u53d8\u91cf\r\n                    threadLocalStr.set(\"bojack horseman\" + threadLocalInt.get());\r\n                    System.out.println(Thread.currentThread().getName() + \"   \" + threadLocalInt.get());\r\n                    System.out.println(Thread.currentThread().getName() + \"   \" + threadLocalStr.get());\r\n                } catch (InterruptedException e) {\r\n                    e.printStackTrace();\r\n                } finally {\r\n                    threadLocalInt.remove();\r\n                    threadLocalStr.remove();\r\n                }\r\n            });\r\n            t.start();\r\n            threads.add(t);\r\n        }\r\n        TimeUnit.SECONDS.sleep(2);\r\n        System.out.println(Thread.currentThread().getName() + \"   \" + threadLocalStr.get());\r\n    }\r\n    \/**\r\n     * Thread-0   2\r\n     * Thread-1   1\r\n     * Thread-0   main\r\n     * Thread-1   main\r\n     * main   main\r\n     * Thread-0   2\r\n     * Thread-0   bojack horseman2\r\n     * Thread-1   1\r\n     * Thread-1   bojack horseman1\r\n     *\/\r\n\r\n}\r\n<\/thread><\/integer><\/string><\/pre>\n","protected":false},"excerpt":{"rendered":"

ThreadLocal\u662f\u7ebf\u7a0bThread\u4e2d\u5c5e\u6027threadLocals\u5373ThreadLocal.ThreadL […]<\/p>\n","protected":false},"author":1903,"featured_media":233107,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[55],"tags":[],"class_list":["post-233086","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-thread"],"acf":[],"_links":{"self":[{"href":"https:\/\/lrxjmw.cn\/wp-json\/wp\/v2\/posts\/233086","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/lrxjmw.cn\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/lrxjmw.cn\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/lrxjmw.cn\/wp-json\/wp\/v2\/users\/1903"}],"replies":[{"embeddable":true,"href":"https:\/\/lrxjmw.cn\/wp-json\/wp\/v2\/comments?post=233086"}],"version-history":[{"count":2,"href":"https:\/\/lrxjmw.cn\/wp-json\/wp\/v2\/posts\/233086\/revisions"}],"predecessor-version":[{"id":233088,"href":"https:\/\/lrxjmw.cn\/wp-json\/wp\/v2\/posts\/233086\/revisions\/233088"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/lrxjmw.cn\/wp-json\/wp\/v2\/media\/233107"}],"wp:attachment":[{"href":"https:\/\/lrxjmw.cn\/wp-json\/wp\/v2\/media?parent=233086"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/lrxjmw.cn\/wp-json\/wp\/v2\/categories?post=233086"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/lrxjmw.cn\/wp-json\/wp\/v2\/tags?post=233086"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}