国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

深入理解ThreadLocal(個(gè)人感覺這個(gè)是比較靠譜的)

2019-11-09 15:48:58
字體:
供稿:網(wǎng)友
先,ThreadLocal 不是用來解決共享對(duì)象的多線程訪問問題的,一般情況下,通過ThreadLocal.set() 到線程中的對(duì)象是該線程自己使用的對(duì)象,其他線程是不需要訪問的,也訪問不到的。各個(gè)線程中訪問的是不同的對(duì)象。 另外,說ThreadLocal使得各線程能夠保持各自獨(dú)立的一個(gè)對(duì)象,并不是通過ThreadLocal.set()來實(shí)現(xiàn)的,而是通過每個(gè)線程中的new 對(duì)象 的操作來創(chuàng)建的對(duì)象,每個(gè)線程創(chuàng)建一個(gè),不是什么對(duì)象的拷貝或副本。通過ThreadLocal.set()將這個(gè)新創(chuàng)建的對(duì)象的引用保存到各線程的自己的一個(gè)map中,每個(gè)線程都有這樣一個(gè)map,執(zhí)行ThreadLocal.get()時(shí),各線程從自己的map中取出放進(jìn)去的對(duì)象,因此取出來的是各自自己線程中的對(duì)象,ThreadLocal實(shí)例是作為map的key來使用的。 如果ThreadLocal.set()進(jìn)去的東西本來就是多個(gè)線程共享的同一個(gè)對(duì)象,那么多個(gè)線程的ThreadLocal.get()取得的還是這個(gè)共享對(duì)象本身,還是有并發(fā)訪問問題。 下面來看一個(gè)hibernate中典型的ThreadLocal的應(yīng)用: java代碼  收藏代碼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,如果還沒有,那么通過sessionFactory().openSession()來創(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可以通過threadSession.get()來得到,里面執(zhí)行的操作實(shí)際是先取得當(dāng)前線程中的ThreadLocalMap,然后將threadSession作為key將對(duì)應(yīng)的值取出。這個(gè)session相當(dāng)于線程的私有變量,而不是public的。 顯然,其他線程中是取不到這個(gè)session的,他們也只能取到自己的ThreadLocalMap中的東西。要是session是多個(gè)線程共享使用的,那還不亂套了。 試想如果不用ThreadLocal怎么來實(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不是用來解決對(duì)象共享訪問問題的,而主要是提供了保持對(duì)象的方法和避免參數(shù)傳遞的方便的對(duì)象訪問方式。歸納了兩點(diǎn): 1。每個(gè)線程中都有一個(gè)自己的ThreadLocalMap類對(duì)象,可以將線程自己的對(duì)象保持到其中,各管各的,線程可以正確的訪問到自己的對(duì)象。 2。將一個(gè)共用的ThreadLocal靜態(tài)實(shí)例作為key,將不同對(duì)象的引用保存到不同線程的ThreadLocalMap中,然后在線程執(zhí)行的各處通過這個(gè)靜態(tài)ThreadLocal實(shí)例的get()方法取得自己線程保存的那個(gè)對(duì)象,避免了將這個(gè)對(duì)象作為參數(shù)傳遞的麻煩。 當(dāng)然如果要把本來線程共享的對(duì)象通過ThreadLocal.set()放到線程中也可以,可以實(shí)現(xiàn)避免參數(shù)傳遞的訪問方式,但是要注意get()到的是那同一個(gè)共享對(duì)象,并發(fā)訪問問題要靠其他手段來解決。但一般來說線程共享的對(duì)象通過設(shè)置為某類的靜態(tài)變量就可以實(shí)現(xiàn)方便的訪問了,似乎沒必要放到線程中。 ThreadLocal的應(yīng)用場(chǎng)合,我覺得最適合的是按線程多實(shí)例(每個(gè)線程對(duì)應(yīng)一個(gè)實(shí)例)的對(duì)象的訪問,并且這個(gè)對(duì)象很多地方都要用到。 下面來看看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 的值。 可以來看一下創(chuàng)建一個(gè)ThreadLocal實(shí)例即new ThreadLocal()時(shí)做了哪些操作,從上面看到構(gòu)造函數(shù)ThreadLocal()里什么操作都沒有,唯一的操作是這句: 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的,用來區(qū)分不同的ThreadLocal實(shí)例,ThreadLocal類主要是作為工具類來使用,那么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 類的代碼太多了,我就不帖了,自己去看源碼吧。 寫了這么多,也不知講明白了沒有,有什么不當(dāng)?shù)牡胤竭€請(qǐng)大家指出來。
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 聂拉木县| 博乐市| 互助| 睢宁县| 广南县| 锡林浩特市| 阜平县| 江源县| 桦南县| 威海市| 石台县| 乌兰浩特市| 沾益县| 遂宁市| 德格县| 荣昌县| 威远县| 象州县| 南皮县| 昌邑市| 中山市| 伊金霍洛旗| 会宁县| 广灵县| 兴义市| 栖霞市| 涞水县| 鹿泉市| 万州区| 建瓯市| 理塘县| 海门市| 灵石县| 永城市| 泸水县| 临汾市| 昌乐县| 新宾| 沈阳市| 探索| 清河县|