为什么jdk源码推荐ThreadLocal使用static
ThreadLocal是線程私有變量,本身是解決多線程環境線程安全,可以說單線程實際上沒必要使用。
既然多線程環境本身不使用static,那么又怎么會線程不安全。所以這個問題本身并不是問題,只是有人沒有理解ThreadLocal的真正使用場景,所以有此疑問。
看看jdk源碼推薦ThreadLocal使用static吧:
/*** This class provides thread-local variables. These variables differ from* their normal counterparts in that each thread that accesses one (via its* {@code get} or {@code set} method) has its own, independently initialized* copy of the variable. {@code ThreadLocal} instances are typically private* static fields in classes that wish to associate state with a thread (e.g.,* a user ID or Transaction ID).** <p>For example, the class below generates unique identifiers local to each* thread.* A thread's id is assigned the first time it invokes {@code ThreadId.get()}* and remains unchanged on subsequent calls.* <pre>* import java.util.concurrent.atomic.AtomicInteger;** public class ThreadId {* // Atomic integer containing the next thread ID to be assigned* private static final AtomicInteger nextId = new AtomicInteger(0);** // Thread local variable containing each thread's ID* private static final ThreadLocal<Integer> threadId =* new ThreadLocal<Integer>() {* @Override protected Integer initialValue() {* return nextId.getAndIncrement();* }* };** // Returns the current thread's unique ID, assigning it if necessary* public static int get() {* return threadId.get();* }* }* </pre>* <p>Each thread holds an implicit reference to its copy of a thread-local* variable as long as the thread is alive and the {@code ThreadLocal}* instance is accessible; after a thread goes away, all of its copies of* thread-local instances are subject to garbage collection (unless other* references to these copies exist).** @author Josh Bloch and Doug Lea* @since 1.2*/
public class ThreadLocal<T> {/*** ThreadLocals rely on per-thread linear-probe hash maps attached* to each thread (Thread.threadLocals and* inheritableThreadLocals). The ThreadLocal objects act as keys,* searched via threadLocalHashCode. This is a custom hash code* (useful only within ThreadLocalMaps) that eliminates collisions* in the common case where consecutively constructed ThreadLocals* are used by the same threads, while remaining well-behaved in* less common cases.*/
這個是Josh Bloch和Doug Lea寫的,再看看他們的著作:《Java并發編程實戰》
再看看jdk中的官方文檔:?
已經說的很明白了,再看看其他答案吧:
?
按照ThreadLocal類的定義
此類提供線程局部變量。這些變量與普通變量不同,每個訪問一個線程(通過其get或set方法)的線程都有其自己的,獨立初始化的變量副本。ThreadLocal實例通常是希望將狀態與線程關聯的類中的私有靜態字段(例如,用戶ID或事務ID)。
這意味著說2個線程t1并t2執行someBMethod(),它們分別結束設置x1&x2(的實例X)。現在,當t1come并執行時,someCMethod()它會獲取x1(它是由它自己設置的)和gets?。t2x2
換句話說,只有一個靜態實例是安全的ThreadLocal,因為在內部調用時它會執行類似的操作set
?
?
Java?源代碼,
-
java.lang.Thread Class包含一個實例變量,如下所示。ThreadLocal.ThreadLocalMap threadLocals = null;
因為threadLocals變量是非靜態的,所以應用程序中的每個線程(即Thread Class的每個實例)將擁有它自己的threadLocals映射副本。
-
該映射的鍵是當前?ThreadLocal實例,而value是您作為參數傳遞給ThreadLocal.set()的值。
-
當您嘗試在內部獲取?as值時
ThreadLocal.get(),它將從Current Thread的ThreadLocalMap獲取。
簡而言之,您是從當前線程對象獲取&設置值,而不是從ThreadLocal對象獲取&設置值。
?
總結
以上是生活随笔為你收集整理的为什么jdk源码推荐ThreadLocal使用static的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mongodb常用语句以及SpringB
- 下一篇: Java反射以及应用