<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

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

    ThreadLocal使用

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

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

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

     

    下面來看看ThreadLocal的實現(xiàn)原理(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都會到這,調(diào)用openSession。
    8.              s = getSessionFactory().openSession();  
    9.              threadSession.set(s);  
    10.          }  
    11.      } catch (HibernateException ex) {  
    12.         throw new InfrastructureException(ex);  
    13.      }  
    14.     return s;  
    15. }
    主站蜘蛛池模板: 一本无码人妻在中文字幕免费| 亚洲AV无码一区二区三区国产| 亚洲av片在线观看| 亚洲精品成人久久久| 一级毛片免费毛片一级毛片免费| 亚洲国产成人在线视频| 亚洲第一黄色网址| 18女人毛片水真多免费| 免费国产高清毛不卡片基地| 亚洲人成电影亚洲人成9999网| 在线观看无码的免费网站| 免费无码一区二区三区蜜桃| 亚洲永久网址在线观看| 亚洲人成亚洲人成在线观看| 成人毛片18女人毛片免费| 两个人看的www免费视频中文| 亚洲欧美黑人猛交群| 亚洲国产精品久久久久婷婷软件| 日本特黄特色aa大片免费| 99国产精品视频免费观看| 杨幂最新免费特级毛片| 97久久国产亚洲精品超碰热| 亚洲一区精品无码| 国产免费无遮挡精品视频| 久久九九兔免费精品6| 国产一级a毛一级a看免费人娇| 亚洲精品无码不卡在线播放| 亚洲成人激情在线| 久久亚洲国产精品五月天婷| 在线观看免费a∨网站| 伊人久久免费视频| 两个人看www免费视频| 黄色a三级免费看| 亚洲日韩精品无码专区加勒比☆| 亚洲福利视频一区| 亚洲日韩小电影在线观看| 亚洲福利在线播放| 精品国产麻豆免费网站| 毛片免费在线观看网站| 国内精品免费麻豆网站91麻豆| 黄色免费在线网站|