欧美性猛交XXXX免费看蜜桃,成人网18免费韩国,亚洲国产成人精品区综合,欧美日韩一区二区三区高清不卡,亚洲综合一区二区精品久久

打開(kāi)APP
userphoto
未登錄

開(kāi)通VIP,暢享免費電子書(shū)等14項超值服

開(kāi)通VIP
正確理解ThreadLocal
首先,ThreadLocal 不是用來(lái)解決共享對象的多線(xiàn)程訪(fǎng)問(wèn)問(wèn)題的,一般情況下,通過(guò)ThreadLocal.set() 到線(xiàn)程中的對象是該線(xiàn)程自己使用的對象,其他線(xiàn)程是不需要訪(fǎng)問(wèn)的,也訪(fǎng)問(wèn)不到的。各個(gè)線(xiàn)程中訪(fǎng)問(wèn)的是不同的對象。

另外,說(shuō)ThreadLocal使得各線(xiàn)程能夠保持各自獨立的一個(gè)對象,并不是通過(guò)ThreadLocal.set()來(lái)實(shí)現的,而是通過(guò)每個(gè)線(xiàn)程中的new 對象 的操作來(lái)創(chuàng )建的對象,每個(gè)線(xiàn)程創(chuàng )建一個(gè),不是什么對象的拷貝或副本。通過(guò)ThreadLocal.set()將這個(gè)新創(chuàng )建的對象的引用保存到各線(xiàn)程的自己的一個(gè)map中,每個(gè)線(xiàn)程都有這樣一個(gè)map,執行ThreadLocal.get()時(shí),各線(xiàn)程從自己的map中取出放進(jìn)去的對象,因此取出來(lái)的是各自自己線(xiàn)程中的對象,ThreadLocal實(shí)例是作為map的key來(lái)使用的。

如果ThreadLocal.set()進(jìn)去的東西本來(lái)就是多個(gè)線(xiàn)程共享的同一個(gè)對象,那么多個(gè)線(xiàn)程的ThreadLocal.get()取得的還是這個(gè)共享對象本身,還是有并發(fā)訪(fǎng)問(wèn)問(wèn)題。

下面來(lái)看一個(gè)hibernate中典型的ThreadLocal的應用:
Java代碼
  1. private static final ThreadLocal threadSession = new ThreadLocal();   
  2.   
  3. public static Session getSession() throws InfrastructureException {   
  4.     Session s = (Session) threadSession.get();   
  5.     try {   
  6.         if (s == null) {   
  7.             s = getSessionFactory().openSession();   
  8.             threadSession.set(s);   
  9.         }   
  10.     } catch (HibernateException ex) {   
  11.         throw new InfrastructureException(ex);   
  12.     }   
  13.     return s;   
  14. }  

可以看到在getSession()方法中,首先判斷當前線(xiàn)程中有沒(méi)有放進(jìn)去session,如果還沒(méi)有,那么通過(guò)sessionFactory().openSession()來(lái)創(chuàng )建一個(gè)session,再將session set到線(xiàn)程中,實(shí)際是放到當前線(xiàn)程的ThreadLocalMap這個(gè)map中,這時(shí),對于這個(gè)session的唯一引用就是當前線(xiàn)程中的那個(gè)ThreadLocalMap(下面會(huì )講到),而threadSession作為這個(gè)值的key,要取得這個(gè)session可以通過(guò)threadSession.get()來(lái)得到,里面執行的操作實(shí)際是先取得當前線(xiàn)程中的ThreadLocalMap,然后將threadSession作為key將對應的值取出。這個(gè)session相當于線(xiàn)程的私有變量,而不是public的。
顯然,其他線(xiàn)程中是取不到這個(gè)session的,他們也只能取到自己的ThreadLocalMap中的東西。要是session是多個(gè)線(xiàn)程共享使用的,那還不亂套了。
試想如果不用ThreadLocal怎么來(lái)實(shí)現呢?可能就要在action中創(chuàng )建session,然后把session一個(gè)個(gè)傳到service和dao中,這可夠麻煩的?;蛘呖梢宰约憾x一個(gè)靜態(tài)的map,將當前thread作為key,創(chuàng )建的session作為值,put到map中,應該也行,這也是一般人的想法,但事實(shí)上,ThreadLocal的實(shí)現剛好相反,它是在每個(gè)線(xiàn)程中有一個(gè)map,而將ThreadLocal實(shí)例作為key,這樣每個(gè)map中的項數很少,而且當線(xiàn)程銷(xiāo)毀時(shí)相應的東西也一起銷(xiāo)毀了,不知道除了這些還有什么其他的好處。

總之,ThreadLocal不是用來(lái)解決對象共享訪(fǎng)問(wèn)問(wèn)題的,而主要是提供了保持對象的方法和避免參數傳遞的方便的對象訪(fǎng)問(wèn)方式。歸納了兩點(diǎn):
1。每個(gè)線(xiàn)程中都有一個(gè)自己的ThreadLocalMap類(lèi)對象,可以將線(xiàn)程自己的對象保持到其中,各管各的,線(xiàn)程可以正確的訪(fǎng)問(wèn)到自己的對象。
2。將一個(gè)共用的ThreadLocal靜態(tài)實(shí)例作為key,將不同對象的引用保存到不同線(xiàn)程的ThreadLocalMap中,然后在線(xiàn)程執行的各處通過(guò)這個(gè)靜態(tài)ThreadLocal實(shí)例的get()方法取得自己線(xiàn)程保存的那個(gè)對象,避免了將這個(gè)對象作為參數傳遞的麻煩。


當然如果要把本來(lái)線(xiàn)程共享的對象通過(guò)ThreadLocal.set()放到線(xiàn)程中也可以,可以實(shí)現避免參數傳遞的訪(fǎng)問(wèn)方式,但是要注意get()到的是那同一個(gè)共享對象,并發(fā)訪(fǎng)問(wèn)問(wèn)題要靠其他手段來(lái)解決。但一般來(lái)說(shuō)線(xiàn)程共享的對象通過(guò)設置為某類(lèi)的靜態(tài)變量就可以實(shí)現方便的訪(fǎng)問(wèn)了,似乎沒(méi)必要放到線(xiàn)程中。

ThreadLocal的應用場(chǎng)合,我覺(jué)得最適合的是按線(xiàn)程多實(shí)例(每個(gè)線(xiàn)程對應一個(gè)實(shí)例)的對象的訪(fǎng)問(wèn),并且這個(gè)對象很多地方都要用到。

下面來(lái)看看ThreadLocal的實(shí)現原理(jdk1.5源碼)
Java代碼
  1. public class ThreadLocal<T> {   
  2.     /**  
  3.      * ThreadLocals rely on per-thread hash maps attached to each thread  
  4.      * (Thread.threadLocals and inheritableThreadLocals).  The ThreadLocal  
  5.      * objects act as keys, searched via threadLocalHashCode.  This is a  
  6.      * custom hash code (useful only within ThreadLocalMaps) that eliminates  
  7.      * collisions in the common case where consecutively constructed  
  8.      * ThreadLocals are used by the same threads, while remaining well-behaved  
  9.      * in less common cases.  
  10.      */  
  11.     private final int threadLocalHashCode = nextHashCode();   
  12.   
  13.     /**  
  14.      * The next hash code to be given out. Accessed only by like-named method.  
  15.      */  
  16.     private static int nextHashCode = 0;   
  17.   
  18.     /**  
  19.      * The difference between successively generated hash codes - turns  
  20.      * implicit sequential thread-local IDs into near-optimally spread  
  21.      * multiplicative hash values for power-of-two-sized tables.  
  22.      */  
  23.     private static final int HASH_INCREMENT = 0x61c88647;   
  24.   
  25.     /**  
  26.      * Compute the next hash code. The static synchronization used here  
  27.      * should not be a performance bottleneck. When ThreadLocals are  
  28.      * generated in different threads at a fast enough rate to regularly  
  29.      * contend on this lock, memory contention is by far a more serious  
  30.      * problem than lock contention.  
  31.      */  
  32.     private static synchronized int nextHashCode() {   
  33.         int h = nextHashCode;   
  34.         nextHashCode = h + HASH_INCREMENT;   
  35.         return h;   
  36.     }   
  37.   
  38.     /**  
  39.      * Creates a thread local variable.  
  40.      */  
  41.     public ThreadLocal() {   
  42.     }   
  43.   
  44.     /**  
  45.      * Returns the value in the current thread's copy of this thread-local  
  46.      * variable.  Creates and initializes the copy if this is the first time  
  47.      * the thread has called this method.  
  48.      *  
  49.      * @return the current thread's value of this thread-local  
  50.      */  
  51.     public T get() {   
  52.         Thread t = Thread.currentThread();   
  53.         ThreadLocalMap map = getMap(t);   
  54.         if (map != null)   
  55.             return (T)map.get(this);   
  56.   
  57.         // Maps are constructed lazily.  if the map for this thread   
  58.         // doesn't exist, create it, with this ThreadLocal and its   
  59.         // initial value as its only entry.   
  60.         T value = initialValue();   
  61.         createMap(t, value);   
  62.         return value;   
  63.     }   
  64.   
  65.     /**  
  66.      * Sets the current thread's copy of this thread-local variable  
  67.      * to the specified value.  Many applications will have no need for  
  68.      * this functionality, relying solely on the {@link #initialValue}  
  69.      * method to set the values of thread-locals.  
  70.      *  
  71.      * @param value the value to be stored in the current threads' copy of  
  72.      *        this thread-local.  
  73.      */  
  74.     public void set(T value) {   
  75.         Thread t = Thread.currentThread();   
  76.         ThreadLocalMap map = getMap(t);   
  77.         if (map != null)   
  78.             map.set(this, value);   
  79.         else  
  80.             createMap(t, value);   
  81.     }   
  82.   
  83.     /**  
  84.      * Get the map associated with a ThreadLocal. Overridden in  
  85.      * InheritableThreadLocal.  
  86.      *  
  87.      * @param  t the current thread  
  88.      * @return the map  
  89.      */  
  90.     ThreadLocalMap getMap(Thread t) {   
  91.         return t.threadLocals;   
  92.     }   
  93.   
  94.     /**  
  95.      * Create the map associated with a ThreadLocal. Overridden in  
  96.      * InheritableThreadLocal.  
  97.      *  
  98.      * @param t the current thread  
  99.      * @param firstValue value for the initial entry of the map  
  100.      * @param map the map to store.  
  101.      */  
  102.     void createMap(Thread t, T firstValue) {   
  103.         t.threadLocals = new ThreadLocalMap(this, firstValue);   
  104.     }   
  105.   
  106.     .......   
  107.   
  108.     /**  
  109.      * ThreadLocalMap is a customized hash map suitable only for  
  110.      * maintaining thread local values. No operations are exported  
  111.      * outside of the ThreadLocal class. The class is package private to  
  112.      * allow declaration of fields in class Thread.  To help deal with  
  113.      * very large and long-lived usages, the hash table entries use  
  114.      * WeakReferences for keys. However, since reference queues are not  
  115.      * used, stale entries are guaranteed to be removed only when  
  116.      * the table starts running out of space.  
  117.      */  
  118.     static class ThreadLocalMap {   
  119.   
  120.     ........   
  121.   
  122.     }   
  123.   
  124. }  


可以看到ThreadLocal類(lèi)中的變量只有這3個(gè)int型:
Java代碼
  1. private final int threadLocalHashCode = nextHashCode();   
  2. private static int nextHashCode = 0;   
  3. private static final int HASH_INCREMENT = 0x61c88647;  

而作為T(mén)hreadLocal實(shí)例的變量只有 threadLocalHashCode 這一個(gè),nextHashCode 和HASH_INCREMENT 是ThreadLocal類(lèi)的靜態(tài)變量,實(shí)際上HASH_INCREMENT是一個(gè)常量,表示了連續分配的兩個(gè)ThreadLocal實(shí)例的threadLocalHashCode值的增量,而nextHashCode 的表示了即將分配的下一個(gè)ThreadLocal實(shí)例的threadLocalHashCode 的值。

可以來(lái)看一下創(chuàng )建一個(gè)ThreadLocal實(shí)例即new ThreadLocal()時(shí)做了哪些操作,從上面看到構造函數ThreadLocal()里什么操作都沒(méi)有,唯一的操作是這句:
Java代碼
  1. private final int threadLocalHashCode = nextHashCode();  

那么nextHashCode()做了什么呢:
Java代碼
  1. private static synchronized int nextHashCode() {   
  2.     int h = nextHashCode;   
  3.     nextHashCode = h + HASH_INCREMENT;   
  4.     return h;   
  5. }  
就是將ThreadLocal類(lèi)的下一個(gè)hashCode值即nextHashCode的值賦給實(shí)例的threadLocalHashCode,然后nextHashCode的值增加HASH_INCREMENT這個(gè)值。

因此ThreadLocal實(shí)例的變量只有這個(gè)threadLocalHashCode,而且是final的,用來(lái)區分不同的ThreadLocal實(shí)例,ThreadLocal類(lèi)主要是作為工具類(lèi)來(lái)使用,那么ThreadLocal.set()進(jìn)去的對象是放在哪兒的呢?

看一下上面的set()方法,兩句合并一下成為
Java代碼
  1. ThreadLocalMap map = Thread.currentThread().threadLocals;  

這個(gè)ThreadLocalMap 類(lèi)是ThreadLocal中定義的內部類(lèi),但是它的實(shí)例卻用在Thread類(lèi)中:
Java代碼
  1. public class Thread implements Runnable {   
  2.     ......   
  3.   
  4.     /* ThreadLocal values pertaining to this thread. This map is maintained  
  5.      * by the ThreadLocal class. */  
  6.     ThreadLocal.ThreadLocalMap threadLocals = null;     
  7.     ......   
  8. }  


再看這句:
Java代碼
  1. if (map != null)   
  2.     map.set(this, value);  

也就是將該ThreadLocal實(shí)例作為key,要保持的對象作為值,設置到當前線(xiàn)程的ThreadLocalMap 中,get()方法同樣大家看了代碼也就明白了,ThreadLocalMap 類(lèi)的代碼太多了,我就不帖了,自己去看源碼吧。

本站僅提供存儲服務(wù),所有內容均由用戶(hù)發(fā)布,如發(fā)現有害或侵權內容,請點(diǎn)擊舉報。
打開(kāi)APP,閱讀全文并永久保存 查看更多類(lèi)似文章
猜你喜歡
類(lèi)似文章
深入JDK源碼之ThreadLocal類(lèi)
一文搞懂 ThreadLocal 原理
Java中ThreadLocal無(wú)鎖化線(xiàn)程封閉實(shí)現原理 – 碼農網(wǎng)
ThreadLocal源碼分析
深入理解 ThreadLocal
深入分析ThreadLocal
更多類(lèi)似文章 >>
生活服務(wù)
分享 收藏 導長(cháng)圖 關(guān)注 下載文章
綁定賬號成功
后續可登錄賬號暢享VIP特權!
如果VIP功能使用有故障,
可點(diǎn)擊這里聯(lián)系客服!

聯(lián)系客服

欧美性猛交XXXX免费看蜜桃,成人网18免费韩国,亚洲国产成人精品区综合,欧美日韩一区二区三区高清不卡,亚洲综合一区二区精品久久