ThreadLocal用法

来源:互联网 发布:grpc python 编辑:程序博客网 时间:2024/05/21 17:11

首先,ThreadLocal 不是用来解决共享对象的多线程访问问题的,一般情况下,通过ThreadLocal.set() 到线程中的对象是该线程自己使用的对象,其他线程是不需要访问的,也访问不到的。各个线程中访问的是不同的对象。 

ThreadLocal用得很好的几个应用场合,值得参考

  1、存放当前session用户:quake want的jert

  2、存放一些context变量,比如webwork的ActionContext

  3、存放session,比如Spring hibernate orm的session


另外,说ThreadLocal使得各线程能够保持各自独立的一个对象,并不是通过ThreadLocal.set()来实现的,而是通过每个线程中的new 对象 的操作来创建的对象,每个线程创建一个,不是什么对象的拷贝或副本。通过ThreadLocal.set()将这个新创建的对象的引用保存到各线程的自己的一个map中,每个线程都有这样一个map,执行ThreadLocal.get()时,各线程从自己的map中取出放进去的对象,因此取出来的是各自自己线程中的对象,ThreadLocal实例是作为map的key来使用的。 

如果ThreadLocal.set()进去的东西本来就是多个线程共享的同一个对象,那么多个线程的ThreadLocal.get()取得的还是这个共享对象本身,还是有并发访问问题。 

下面来看一个hibernate中典型的ThreadLocal的应用: 
  1.   
  2. public static Session getSession() throws InfrastructureException {   
  3.     Session s = (Session) threadSession.get();   
  4.     try {   
  5.         if (s == null) {   
  6.             s = getSessionFactory().openSession();   
  7.             threadSession.set(s);   
  8.         }   
  9.     } catch (HibernateException ex) {   
  10.         throw new InfrastructureException(ex);   
  11.     }   
  12.     return s;   
  13. }  
    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()方法中,首先判断当前线程中有没有放进去session,如果还没有,那么通过sessionFactory().openSession()来创建一个session,再将session set到线程中,实际是放到当前线程的ThreadLocalMap这个map中,这时,对于这个session的唯一引用就是当前线程中的那个ThreadLocalMap(下面会讲到),而threadSession作为这个值的key,要取得这个session可以通过threadSession.get()来得到,里面执行的操作实际是先取得当前线程中的ThreadLocalMap,然后将threadSession作为key将对应的值取出。这个session相当于线程的私有变量,而不是public的。 
显然,其他线程中是取不到这个session的,他们也只能取到自己的ThreadLocalMap中的东西。要是session是多个线程共享使用的,那还不乱套了。 
试想如果不用ThreadLocal怎么来实现呢?可能就要在action中创建session,然后把session一个个传到service和dao中,这可够麻烦的。或者可以自己定义一个静态的map,将当前thread作为key,创建的session作为值,put到map中,应该也行,这也是一般人的想法,但事实上,ThreadLocal的实现刚好相反,它是在每个线程中有一个map,而将ThreadLocal实例作为key,这样每个map中的项数很少,而且当线程销毁时相应的东西也一起销毁了,不知道除了这些还有什么其他的好处。 

总之,ThreadLocal不是用来解决对象共享访问问题的,而主要是提供了保持对象的方法和避免参数传递的方便的对象访问方式。归纳了两点: 
1。每个线程中都有一个自己的ThreadLocalMap类对象,可以将线程自己的对象保持到其中,各管各的,线程可以正确的访问到自己的对象。 
2。将一个共用的ThreadLocal静态实例作为key,将不同对象的引用保存到不同线程的ThreadLocalMap中,然后在线程执行的各处通过这个静态ThreadLocal实例的get()方法取得自己线程保存的那个对象,避免了将这个对象作为参数传递的麻烦。
 

当然如果要把本来线程共享的对象通过ThreadLocal.set()放到线程中也可以,可以实现避免参数传递的访问方式,但是要注意get()到的是那同一个共享对象,并发访问问题要靠其他手段来解决。但一般来说线程共享的对象通过设置为某类的静态变量就可以实现方便的访问了,似乎没必要放到线程中。 

ThreadLocal的应用场合,我觉得最适合的是按线程多实例(每个线程对应一个实例)的对象的访问,并且这个对象很多地方都要用到。 

下面来看看ThreadLocal的实现原理(jdk1.5源码) 

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


可以看到ThreadLocal类中的变量只有这3个int型: 

  1. private static int nextHashCode = 0;   
  2. private static final int HASH_INCREMENT = 0x61c88647;  
    private final int threadLocalHashCode = nextHashCode();    private static int nextHashCode = 0;    private static final int HASH_INCREMENT = 0x61c88647;


而作为ThreadLocal实例的变量只有 threadLocalHashCode 这一个,nextHashCode 和HASH_INCREMENT 是ThreadLocal类的静态变量,实际上HASH_INCREMENT是一个常量,表示了连续分配的两个ThreadLocal实例的threadLocalHashCode值的增量,而nextHashCode 的表示了即将分配的下一个ThreadLocal实例的threadLocalHashCode 的值。 

可以来看一下创建一个ThreadLocal实例即new ThreadLocal()时做了哪些操作,从上面看到构造函数ThreadLocal()里什么操作都没有,唯一的操作是这句: 

    private final int threadLocalHashCode = nextHashCode();


那么nextHashCode()做了什么呢: 

  1.     int h = nextHashCode;   
  2.     nextHashCode = h + HASH_INCREMENT;   
  3.     return h;   
  4. }  
    private static synchronized int nextHashCode() {        int h = nextHashCode;        nextHashCode = h + HASH_INCREMENT;        return h;    }

就是将ThreadLocal类的下一个hashCode值即nextHashCode的值赋给实例的threadLocalHashCode,然后nextHashCode的值增加HASH_INCREMENT这个值。 

因此ThreadLocal实例的变量只有这个threadLocalHashCode,而且是final的,用来区分不同的ThreadLocal实例,ThreadLocal类主要是作为工具类来使用,那么ThreadLocal.set()进去的对象是放在哪儿的呢? 

看一下上面的set()方法,两句合并一下成为 

        ThreadLocalMap map = Thread.currentThread().threadLocals;


这个ThreadLocalMap 类是ThreadLocal中定义的内部类,但是它的实例却用在Thread类中: 

  1.     ......   
  2.   
  3.     /* ThreadLocal values pertaining to this thread. This map is maintained  
  4.      * by the ThreadLocal class. */  
  5.     ThreadLocal.ThreadLocalMap threadLocals = null;     
  6.     ......   
  7. }  
public class Thread implements Runnable {    ......    /* ThreadLocal values pertaining to this thread. This map is maintained     * by the ThreadLocal class. */    ThreadLocal.ThreadLocalMap threadLocals = null;      ......}



再看这句: 

  1.     map.set(this, value);  
        if (map != null)            map.set(this, value);


也就是将该ThreadLocal实例作为key,要保持的对象作为值,设置到当前线程的ThreadLocalMap 中,get()方法同样大家看了代码也就明白了,ThreadLocalMap 类的代码:

ThreadLocalMap是java.lang.ThreadLocal的静态内部类。ThreadLocalMap表面看起来至少实现类似hashmap的功能,但是仔细分析它却有下面的属性。

首先,它只是尽量的让value保持在哈希值的位置或后面,

其次,它提供了对不同key(这里是ThreadLocal)对象的但hashCode相同的存储的支持。

最后,它对Key的引用是弱引用。这个和WeakHashMap一致。但这个和hashMap有点不一样,hashMap要使用用弱引用的话,

一般是对value进行弱引用的,而不是key.

也许有一天我们在自己的程序中需要类似ThreadLocalMap的功能。

以下是从ThreadLocalMap简化而来的代码:

其中Key对应JDK中的ThreadLocal

class Key {

    final int hashCode = nextHashCode();

    static AtomicInteger nextHashCode =

    new AtomicInteger();

    static final int HASH_INCREMENT = 0x61c88647;

    static int nextHashCode() {

    return nextHashCode.getAndAdd(HASH_INCREMENT);

    }

}

class ThreadLocalMap {

        static class Entry extends WeakReference<Key> {

            Object value;

            Entry(Key k, Object v) {

                super(k);

                value = v;

            }

        }

         //初始值,必须是2的n次方

        private static final int INITIAL_CAPACITY = 16;

        /**

         * The table, resized as necessary.

         * table.length MUST always be a power of two.

         */

        private Entry[] table;

        private int size = 0;

        /**

         * The next size value at which to resize.

         */

        private int threshold; // Default to 0

        /**

         * Set the resize threshold to maintain at worst a 2/3 load factor.

         */

        private void setThreshold(int len) {

            threshold = len * 2 / 3;

        }

        private static int nextIndex(int i, int len) {

            return ((i + 1 < len) ? i + 1 : 0);

        }

        private static int prevIndex(int i, int len) {

            return ((i - 1 >= 0) ? i - 1 : len - 1);

        }

        /**

         * Construct a new map initially containing (firstKey, firstValue).

         * ThreadLocalMaps are constructed lazily, so we only create

         * one when we have at least one entry to put in it.

         */

        ThreadLocalMap(Key firstKey, Object firstValue) {

            table = new Entry[INITIAL_CAPACITY];

            int i = firstKey.hashCode & (INITIAL_CAPACITY - 1);

            table = new Entry(firstKey, firstValue);

            size = 1;

            setThreshold(INITIAL_CAPACITY);

        }

        private Entry getEntry(Key key) {

            int i = key.hashCode & (table.length - 1);

            Entry e = table[i];

            if (e != null && e.get() == key)

                return e;

            else

                return getEntryAfterMiss(key, i, e);

        }

        private Entry getEntryAfterMiss(Key key, int i, Entry e) {

            Entry[] tab = table[i];

            int len = tab.length;

            while (e != null) {

                Key k = e.get();

                if (k == key)

                    return e;

                if (k == null)

                    expungeStaleEntry(i);

                else

                    i = nextIndex(i, len);

                e = tab[i];

            }

            return null;

        }

       private void set(Key key, Object value) {

            Entry[] tab = table;

            int len = tab.length;

            int i = key.hashCode & (len-1);

            for (Entry e = tab[i]; e != null; e = tab[i = nextIndex(i, len)]) {

                Key k = e.get();

                if (k == key) {

                    e.value = value;

                    return;

                }

                if (k == null) {

                    replaceStaleEntry(key, value, i);

                    return;

                }

            }

            tab = new Entry(key, value);

            int sz = ++size;

            if (!cleanSomeSlots(i, sz) && sz >= threshold)

                rehash();

        }

        private void remove(Key key) {

            Entry[] tab = table;

            int len = tab.length;

            int i = key.hashCode & (len-1);

            for (Entry e = tab;

         e != null;

         e = tab[i = nextIndex(i, len)]) {

                if (e.get() == key) {

                    e.clear();

                    expungeStaleEntry(i);

                    return;

                }

            }

        }

        private void replaceStaleEntry(Key key, Object value,

                                       int staleSlot) {

            Entry[] tab = table;

            int len = tab.length;

            Entry e;

            int slotToExpunge = staleSlot;

            for (int i = prevIndex(staleSlot, len);

         (e = tab) != null;

                 i = prevIndex(i, len))

                if (e.get() == null)

                    slotToExpunge = i;

            for (int i = nextIndex(staleSlot, len);

         (e = tab) != null;

                 i = nextIndex(i, len)) {

                Key k = e.get();

                if (k == key) {

                    e.value = value;

 

                    tab = tab[staleSlot];

                    tab[staleSlot] = e;

                    // Start expunge at preceding stale entry if it exists

                    if (slotToExpunge == staleSlot)

                        slotToExpunge = i;

                    cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);

                    return;

                }

                if (k == null && slotToExpunge == staleSlot)

                    slotToExpunge = i;

            }

            // If key not found, put new entry in stale slot

            tab[staleSlot].value = null;  

            tab[staleSlot] = new Entry(key, value);

            // If there are any other stale entries in run, expunge them

            if (slotToExpunge != staleSlot)

                cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);

        }

        /**擦除staleSlot的Entry。

        *调整所有不在哈希映射位置的value的位置,让它尽量在哈希映射的位置

        */

        private int expungeStaleEntry(int staleSlot) {

            Entry[] tab = table;

            int len = tab.length;

            tab[staleSlot].value = null;  

            tab[staleSlot] = null;

            size--;

            // Rehash until we encounter null

            Entry e;

            int i;

            for (i = nextIndex(staleSlot, len);

         (e = tab) != null;

                 i = nextIndex(i, len)) {

                Key k = e.get();

                if (k == null) {

                    e.value = null;

                    tab = null;

                    size--;

                } else {

                    int h = k.hashCode & (len - 1);

                    if (h != i) {

                        tab = null;

 

                        // Unlike Knuth 6.4 Algorithm R, we must scan until

                        // null because multiple entries could have been stale.

                        while (tab[h] != null)

                            h = nextIndex(h, len);

                        tab[h] = e;

                    }

                }

            }

            return i;

        }

        private boolean cleanSomeSlots(int i, int n) {

            boolean removed = false;

            Entry[] tab = table;

            int len = tab.length;

            do {

                i = nextIndex(i, len);

                Entry e = tab;

                if (e != null && e.get() == null) {

                    n = len;

                    removed = true;

                    i = expungeStaleEntry(i);

                }

            } while ( (n >>>= 1) != 0);

            return removed;

        }

        private void rehash() {

            expungeStaleEntries();

            // Use lower threshold for doubling to avoid hysteresis

            if (size >= threshold - threshold / 4)

                resize();

        }

        private void resize() {

            Entry[] oldTab = table;

            int oldLen = oldTab.length;

            int newLen = oldLen * 2;

            Entry[] newTab = new Entry[newLen];

            int count = 0;

 

            for (int j = 0; j < oldLen; ++j) {

                Entry e = oldTab[j];

                if (e != null) {

                    Key k = e.get();

                    if (k == null) {

                        e.value = null; // Help the GC

                    } else {

                        int h = k.hashCode & (newLen - 1);

                        while (newTab[h] != null)

                            h = nextIndex(h, newLen);

                        newTab[h] = e;

                        count++;

                    }

                }

            }

            setThreshold(newLen);

            size = count;

            table = newTab;

        }

        private void expungeStaleEntries() {

            Entry[] tab = table;

            int len = tab.length;

            for (int j = 0; j < len; j++) {

                Entry e = tab[j];

                if (e != null && e.get() == null)

                    expungeStaleEntry(j);

            }

        }

    }


0 0
原创粉丝点击