posts - 0, comments - 77, trackbacks - 0, articles - 356
            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理

          ThreadLocal使用

          Posted on 2008-04-24 09:32 semovy 閱讀(973) 評論(0)  編輯  收藏 所屬分類: JAVA基礎
           TheadLocal包含了一組get(),set(Object)方法,可以獲得當前線程的放進去的對象。

              ThreadLocal 不是用來解決共享對象的多線程訪問問題的,一般情況下,通過ThreadLocal.set() 到線程中的對象是該線程自己使用的對象,其他線程是不需要訪問的,也訪問不到的。各個線程中訪問的是不同的對象。

              另外,說ThreadLocal使得各線程能夠保持各自獨立的一個對象,這個對象的創建并不是通過ThreadLocal.set()來實現的,set()并不會做什么對象的拷貝,而是每個線程之前已經創建好的對象。通 過ThreadLocal.set()將這個新創建的對象的引用以當前線程為key,保存TheadLocal的一個map中,執行 ThreadLocal.get()時,各線程從map中取出以當前線程為key的對象,因此取出來的是各自自己線程中的對象。

           

          下面來看看ThreadLocal的實現原理(jdk1.5源碼)

          代碼
          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.      }

          以hibernate中典型的ThreadLocal的應用:
          代碼
          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.           //每一個線程第一次使用getSession都會到這,調用openSession。
          8.              s = getSessionFactory().openSession();  
          9.              threadSession.set(s);  
          10.          }  
          11.      } catch (HibernateException ex) {  
          12.         throw new InfrastructureException(ex);  
          13.      }  
          14.     return s;  
          15. }
          主站蜘蛛池模板: 乌鲁木齐县| 赣州市| 布拖县| 东乌珠穆沁旗| 巩义市| 营山县| 白朗县| 呈贡县| 改则县| 汉寿县| 庄河市| 江口县| 肥城市| 南安市| 岗巴县| 和平县| 察哈| 永州市| 大庆市| 龙里县| 外汇| 浙江省| 普安县| 迁安市| 林口县| 岑溪市| 冕宁县| 黄平县| 巍山| 旬阳县| 鹿泉市| 新源县| 武川县| 屯留县| 泰顺县| 历史| 英超| 九龙坡区| 荣昌县| 泰宁县| 棋牌|