轉(zhuǎn)載:http://www.codeceo.com/article/java-threadlocal-deep-learn.html
首先锻梳,ThreadLocal不是用來(lái)解決共享對(duì)象的多線程訪問(wèn)問(wèn)題的,一般情況下宋舷,通過(guò)ThreadLocal.set() 到線程中的對(duì)象是該線程自己使用的對(duì)象,其他線程是不需要訪問(wèn)的签夭,也訪問(wèn)不到的授嘀。各個(gè)線程中訪問(wèn)的是不同的對(duì)象锰蓬。
另外,說(shuō)ThreadLocal使得各線程能夠保持各自獨(dú)立的一個(gè)對(duì)象赋咽,并不是通過(guò)ThreadLocal.set()來(lái)實(shí)現(xiàn)的旧噪,而是通過(guò)每個(gè)線程中的new 對(duì)象 的操作來(lái)創(chuàng)建的對(duì)象,每個(gè)線程創(chuàng)建一個(gè)脓匿,不是什么對(duì)象的拷貝或副本淘钟。通過(guò)ThreadLocal.set()將這個(gè)新創(chuàng)建的對(duì)象的引用保存到各線程的自己的一個(gè)map中,每個(gè)線程都有這樣一個(gè)map亦镶,執(zhí)行ThreadLocal.get()時(shí)日月,各線程從自己的map中取出放進(jìn)去的對(duì)象,因此取出來(lái)的是各自自己線程中的對(duì)象缤骨,ThreadLocal實(shí)例是作為map的key來(lái)使用的爱咬。
如果ThreadLocal.set()進(jìn)去的東西本來(lái)就是多個(gè)線程共享的同一個(gè)對(duì)象,那么多個(gè)線程的ThreadLocal.get()取得的還是這個(gè)共享對(duì)象本身绊起,還是有并發(fā)訪問(wèn)問(wèn)題精拟。
下面來(lái)看一個(gè)hibernate中典型的ThreadLocal的應(yīng)用:
private static final ThreadLocal threadSession = new ThreadLocal();
public static Session getSession() throws InfrastructureException {
Session s = (Session) threadSession.get();
try {
if (s == null) {
s = getSessionFactory().openSession();
threadSession.set(s);
}
} catch (HibernateException ex) {
throw new InfrastructureException(ex);
}
return s;
}
可以看到在getSession()方法中,首先判斷當(dāng)前線程中有沒有放進(jìn)去session虱歪,如果還沒有蜂绎,那么通過(guò)sessionFactory().openSession()來(lái)創(chuàng)建一個(gè)session,再將session set到線程中笋鄙,實(shí)際是放到當(dāng)前線程的ThreadLocalMap這個(gè)map中师枣,這時(shí),對(duì)于這個(gè)session的唯一引用就是當(dāng)前線程中的那個(gè)ThreadLocalMap(下面會(huì)講到)萧落,而threadSession作為這個(gè)值的key践美,要取得這個(gè)session可以通過(guò)threadSession.get()來(lái)得到洗贰,里面執(zhí)行的操作實(shí)際是先取得當(dāng)前線程中的ThreadLocalMap,然后將threadSession作為key將對(duì)應(yīng)的值取出陨倡。這個(gè)session相當(dāng)于線程的私有變量敛滋,而不是public的。 顯然兴革,其他線程中是取不到這個(gè)session的绎晃,他們也只能取到自己的ThreadLocalMap中的東西。要是session是多個(gè)線程共享使用的杂曲,那還不亂套了庶艾。 試想如果不用ThreadLocal怎么來(lái)實(shí)現(xiàn)呢?可能就要在action中創(chuàng)建session解阅,然后把session一個(gè)個(gè)傳到service和dao中落竹,這可夠麻煩的』醭或者可以自己定義一個(gè)靜態(tài)的map述召,將當(dāng)前thread作為key,創(chuàng)建的session作為值蟹地,put到map中积暖,應(yīng)該也行,這也是一般人的想法怪与,但事實(shí)上夺刑,ThreadLocal的實(shí)現(xiàn)剛好相反,它是在每個(gè)線程中有一個(gè)map分别,而將ThreadLocal實(shí)例作為key遍愿,這樣每個(gè)map中的項(xiàng)數(shù)很少,而且當(dāng)線程銷毀時(shí)相應(yīng)的東西也一起銷毀了耘斩,不知道除了這些還有什么其他的好處沼填。
總之,ThreadLocal不是用來(lái)解決對(duì)象共享訪問(wèn)問(wèn)題的括授,而主要是提供了保持對(duì)象的方法和避免參數(shù)傳遞的方便的對(duì)象訪問(wèn)方式坞笙。歸納了兩點(diǎn): 1。每個(gè)線程中都有一個(gè)自己的ThreadLocalMap類對(duì)象荚虚,可以將線程自己的對(duì)象保持到其中薛夜,各管各的,線程可以正確的訪問(wèn)到自己的對(duì)象版述。 2梯澜。將一個(gè)共用的ThreadLocal靜態(tài)實(shí)例作為key,將不同對(duì)象的引用保存到不同線程的ThreadLocalMap中渴析,然后在線程執(zhí)行的各處通過(guò)這個(gè)靜態(tài)ThreadLocal實(shí)例的get()方法取得自己線程保存的那個(gè)對(duì)象腊徙,避免了將這個(gè)對(duì)象作為參數(shù)傳遞的麻煩简十。
當(dāng)然如果要把本來(lái)線程共享的對(duì)象通過(guò)ThreadLocal.set()放到線程中也可以,可以實(shí)現(xiàn)避免參數(shù)傳遞的訪問(wèn)方式撬腾,但是要注意get()到的是那同一個(gè)共享對(duì)象,并發(fā)訪問(wèn)問(wèn)題要靠其他手段來(lái)解決恢恼。但一般來(lái)說(shuō)線程共享的對(duì)象通過(guò)設(shè)置為某類的靜態(tài)變量就可以實(shí)現(xiàn)方便的訪問(wèn)了民傻,似乎沒必要放到線程中。
ThreadLocal的應(yīng)用場(chǎng)合场斑,我覺得最適合的是按線程多實(shí)例(每個(gè)線程對(duì)應(yīng)一個(gè)實(shí)例)的對(duì)象的訪問(wèn)漓踢,并且這個(gè)對(duì)象很多地方都要用到。
下面來(lái)看看ThreadLocal的實(shí)現(xiàn)原理(jdk1.5源碼)
public class ThreadLocal<T> {
/**
* ThreadLocals rely on per-thread 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.
*/
private final int threadLocalHashCode = nextHashCode();
/**
* The next hash code to be given out. Accessed only by like-named method.
*/
private static int nextHashCode = 0;
/**
* The difference between successively generated hash codes - turns
* implicit sequential thread-local IDs into near-optimally spread
* multiplicative hash values for power-of-two-sized tables.
*/
private static final int HASH_INCREMENT = 0x61c88647;
/**
* Compute the next hash code. The static synchronization used here
* should not be a performance bottleneck. When ThreadLocals are
* generated in different threads at a fast enough rate to regularly
* contend on this lock, memory contention is by far a more serious
* problem than lock contention.
*/
private static synchronized int nextHashCode() {
int h = nextHashCode;
nextHashCode = h + HASH_INCREMENT;
return h;
}
/**
* Creates a thread local variable.
*/
public ThreadLocal() {
}
/**
* Returns the value in the current thread's copy of this thread-local
* variable. Creates and initializes the copy if this is the first time
* the thread has called this method.
*
* @return the current thread's value of this thread-local
*/
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
return (T)map.get(this);
// Maps are constructed lazily. if the map for this thread
// doesn't exist, create it, with this ThreadLocal and its
// initial value as its only entry.
T value = initialValue();
createMap(t, value);
return value;
}
/**
* Sets the current thread's copy of this thread-local variable
* to the specified value. Many applications will have no need for
* this functionality, relying solely on the {@link #initialValue}
* method to set the values of thread-locals.
*
* @param value the value to be stored in the current threads' copy of
* this thread-local.
*/
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
/**
* Get the map associated with a ThreadLocal. Overridden in
* InheritableThreadLocal.
*
* @param t the current thread
* @return the map
*/
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
/**
* Create the map associated with a ThreadLocal. Overridden in
* InheritableThreadLocal.
*
* @param t the current thread
* @param firstValue value for the initial entry of the map
* @param map the map to store.
*/
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
.......
/**
* ThreadLocalMap is a customized hash map suitable only for
* maintaining thread local values. No operations are exported
* outside of the ThreadLocal class. The class is package private to
* allow declaration of fields in class Thread. To help deal with
* very large and long-lived usages, the hash table entries use
* WeakReferences for keys. However, since reference queues are not
* used, stale entries are guaranteed to be removed only when
* the table starts running out of space.
*/
static class ThreadLocalMap {
........
}
}
可以看到ThreadLocal類中的變量只有這3個(gè)int型:
private final int threadLocalHashCode = nextHashCode();
private static int nextHashCode = 0;
private static final int HASH_INCREMENT = 0x61c88647;
而作為ThreadLocal實(shí)例的變量只有 threadLocalHashCode 這一個(gè)漏隐,nextHashCode 和HASH_INCREMENT 是ThreadLocal類的靜態(tài)變量喧半,實(shí)際上HASH_INCREMENT是一個(gè)常量,表示了連續(xù)分配的兩個(gè)ThreadLocal實(shí)例的threadLocalHashCode值的增量青责,而nextHashCode 的表示了即將分配的下一個(gè)ThreadLocal實(shí)例的threadLocalHashCode 的值挺据。
可以來(lái)看一下創(chuàng)建一個(gè)ThreadLocal實(shí)例即new ThreadLocal()時(shí)做了哪些操作,從上面看到構(gòu)造函數(shù)ThreadLocal()里什么操作都沒有脖隶,唯一的操作是這句:
private final int threadLocalHashCode = nextHashCode();
那么nextHashCode()做了什么呢:
private static synchronized int nextHashCode() {
int h = nextHashCode;
nextHashCode = h + HASH_INCREMENT;
return h;
}
就是將ThreadLocal類的下一個(gè)hashCode值即nextHashCode的值賦給實(shí)例的threadLocalHashCode扁耐,然后nextHashCode的值增加HASH_INCREMENT這個(gè)值。
因此ThreadLocal實(shí)例的變量只有這個(gè)threadLocalHashCode产阱,而且是final的婉称,用來(lái)區(qū)分不同的ThreadLocal實(shí)例,ThreadLocal類主要是作為工具類來(lái)使用构蹬,那么ThreadLocal.set()進(jìn)去的對(duì)象是放在哪兒的呢王暗?
看一下上面的set()方法,兩句合并一下成為
ThreadLocalMap map = Thread.currentThread().threadLocals;
這個(gè)ThreadLocalMap 類是ThreadLocal中定義的內(nèi)部類庄敛,但是它的實(shí)例卻用在Thread類中:
public class Thread implements Runnable {
......
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;
......
}
再看這句:
if (map != null)
map.set(this, value);
也就是將該ThreadLocal實(shí)例作為key俗壹,要保持的對(duì)象作為值,設(shè)置到當(dāng)前線程的ThreadLocalMap 中铐姚,get()方法同樣大家看了代碼也就明白了策肝。