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)前線程中有沒(méi)有放進(jìn)去session,如果還沒(méi)有,那么通過(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)了,似乎沒(méi)必要放到線程中。 ThreadLocal的應(yīng)用場(chǎng)合,我覺(jué)得最適合的是按線程多實(shí)例(每個(gè)線程對(duì)應(yīng)一個(gè)實(shí)例)的對(duì)象的訪問(wèn),并且這個(gè)對(duì)象很多地方都要用到。 下面來(lái)看看ThreadLocal的實(shí)現(xiàn)原理(jdk1.5源碼) Java代碼
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 * multapplications 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型: Java代碼
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()里什么操作都沒(méi)有,唯一的操作是這句: Java代碼
private final int threadLocalHashCode = nextHashCode(); 那么nextHashCode()做了什么呢: Java代碼
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()方法,兩句合并一下成為 Java代碼
ThreadLocalMap map = Thread.currentThread().threadLocals; 這個(gè)ThreadLocalMap 類是ThreadLocal中定義的內(nèi)部類,但是它的實(shí)例卻用在Thread類中: Java代碼
public class Thread implements Runnable { ...... /* ThreadLocal values pertaining to this thread. This map is maintained * by the ThreadLocal class. */ ThreadLocal.ThreadLocalMap threadLocals = null; ...... } 再看這句: Java代碼
if (map != null) map.set(this, value); 也就是將該ThreadLocal實(shí)例作為key,要保持的對(duì)象作為值,設(shè)置到當(dāng)前線程的ThreadLocalMap 中,get()方法同樣大家看了代碼也就明白了,ThreadLocalMap 類的代碼太多了,我就不帖了,自己去看源碼吧。 寫了這么多,也不知講明白了沒(méi)有,有什么不當(dāng)?shù)牡胤竭€請(qǐng)大家指出來(lái)。
|
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注