<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 :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理

    ThreadLocal使用

    Posted on 2008-04-24 09:32 semovy 閱讀(971) 評論(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. }
    主站蜘蛛池模板: **aaaaa毛片免费同男同女| 两个人看的www免费| 成人免费的性色视频| 国产精品亚洲精品日韩已满| 中文字幕无码免费久久9一区9| 亚洲AV无码之日韩精品| 免费VA在线观看无码| 亚洲国模精品一区| 国产免费播放一区二区| 亚洲精品无码久久久久去q| 久久精品成人免费观看| 久久亚洲美女精品国产精品| 精品成在人线AV无码免费看| 亚洲国产综合第一精品小说| 成人毛片免费观看视频大全| 亚洲国产区男人本色| 亚洲AⅤ永久无码精品AA| 久久免费国产精品| 久久亚洲精品中文字幕无码 | 黄色三级三级免费看| 亚洲日韩中文在线精品第一 | 国产成人无码精品久久久免费| 国产午夜亚洲精品午夜鲁丝片 | 国产成人免费网站| 色综合久久精品亚洲国产| 亚洲XX00视频| 久艹视频在线免费观看| 亚洲va在线va天堂成人| 免费大学生国产在线观看p| 插鸡网站在线播放免费观看| 亚洲精品视频专区| 免费永久在线观看黄网站| 最近免费中文字幕MV在线视频3| 亚洲美女一区二区三区| 日本媚薬痉挛在线观看免费| 亚洲精品视频免费观看| 亚洲成a人片77777群色| 亚洲?v女人的天堂在线观看| 57pao国产成视频免费播放| 精品亚洲视频在线| 久久亚洲精品无码AV红樱桃|