[java] ThreadLocal类解析

版权声明:未经博主同意,谢绝转载!(请尊重原创,感谢) https://blog.csdn.net/topdeveloperr/article/details/82180653

概述

该类的作用是提供线程局部(thread-local)的变量, 这些变量与正常变量的不同之处在于(通过其get或set方法)访问一个线程的每个线程都有自己的独立初始化的变量副本。ThreadLocal实例通常是希望存储状态与线程(例如,用户ID或事务ID)关联的私有静态字段。

例如,下面的类生成每个线程本地的唯一标识符。第一次调用ThreadId.get方法时,分配一个线程的ID,在后续调用中保持不变。

import java.util.concurrent.atomic.AtomicInteger;

public class ThreadId {
     // Atomic integer containing the next thread ID to be assigned
     private static final AtomicInteger nextId = new AtomicInteger(0);

     // Thread local variable containing each thread's ID
     private static final ThreadLocal<Integer> threadId =
         new ThreadLocal<Integer>() {
             @Override 
             protected Integer initialValue() {
                 return nextId.getAndIncrement();
         }
     };

     // Returns the current thread's unique ID, assigning it if necessary
     public static int get() {
         return threadId.get();
     }
 }

每个线程都保持对线程本地变量的副本的隐式引用,只要线程是活的并且ThreadLocal实例是可访问的;在线程离开后,线程本地实例的所有副本都由垃圾收集的处理(除非对这些副本有其他引用)。

Set方法

代码实现如下:

 public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

首先根据调用这个方法的对象获取当前线程,然后获取属于这个线程的ThreadLocalMap实例。 ThreadLocalMap是ThreadLocal的一个内部类,这个类的代码占据了ThreadLocal类的一半还多。可见其重要性。Threadlocal的方法都是基于这个类实现的。

从上面代码我们可以看到,如果map不为空就调用set方法

/**
         * Set the value associated with key.
         *
         * @param key the thread local object
         * @param value the value to be set
         */
        private void set(ThreadLocal<?> key, Object value) {

            // We don't use a fast path as with get() because it is at
            // least as common to use set() to create new entries as
            // it is to replace existing ones, in which case, a fast
            // path would fail more often than not.

            Entry[] tab = table;
            int len = tab.length;
            int i = key.threadLocalHashCode & (len-1);

            for (Entry e = tab[i];
                 e != null;
                 e = tab[i = nextIndex(i, len)]) {
                ThreadLocal<?> k = e.get();

                if (k == key) {
                    e.value = value;
                    return;
                }

                if (k == null) {
                    replaceStaleEntry(key, value, i);
                    return;
                }
            }

            tab[i] = new Entry(key, value);
            int sz = ++size;
            if (!cleanSomeSlots(i, sz) && sz >= threshold)
                rehash();
        }

Key即为传入的参数this,即调用这个set方法的ThreadLocal实例,我们知道每个线程都会有自己对应的ThreadLocal实例,而这里把这个实例拿来作为了map的key,因此,这就可以解释清楚了为什么ThreadLocal是线程之间隔离的。

实现的逻辑比较简单:

根据传入的key,借助了Unsafe类去计算它的hashcode值,然后value不用做任何其他处理。最后是存储在了一个Entry类型的数组里面。

Entry则是ThreadLocalMap这个类的有一个内部类,定义如下:

 static class Entry extends WeakReference<ThreadLocal<?>> {
            /** The value associated with this ThreadLocal. */
            Object value;

            Entry(ThreadLocal<?> k, Object v) {
                super(k);
                value = v;
            }
        }

可以看到,这个类里面有一个Object类型的成员变量value,这个成员变量就是我们拿来存储值的变量。

get方法

实现代码如下:

 /**
     * Returns the value in the current thread's copy of this
     * thread-local variable.  If the variable has no value for the
     * current thread, it is first initialized to the value returned
     * by an invocation of the {@link #initialValue} method.
     *
     * @return the current thread's value of this thread-local
     */
    public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }

有一个很有意思的问题,这个方法不是get方法吗?那它为什么没有参数,没有key呢?其实在分析set方法的时候我们已经回答了这个问题了,ThreadLocal的map的key是ThreadLocal实例本身。再看代码:首先仍旧是获取了当前线程,再去拿了它的ThreadLocalMap,这个时候,直接去调用了这个map的getEntry方法,然后传入的参数是this ,即这个ThreadLocal对象本身。非常巧妙的逻辑。

remove方法

  public void remove() {
         ThreadLocalMap m = getMap(Thread.currentThread());
         if (m != null)
             m.remove(this);
     }

调用了ThreadLocalMap的remove方法,参数是ThreadLocal实例,也就是map的key,即这里的this。实现如下

     /**
         * Remove the entry for key.
         */
        private void remove(ThreadLocal<?> key) {
            Entry[] tab = table;
            int len = tab.length;
            int i = key.threadLocalHashCode & (len-1);
            for (Entry e = tab[i];
                 e != null;
                 e = tab[i = nextIndex(i, len)]) {
                if (e.get() == key) {
                    e.clear();
                    expungeStaleEntry(i);
                    return;
                }
            }
        }

遍历table,找到这个key对于的Entry,然后把它的值设为null。

ThreadLocal Map定义

在ThreadLocal类中,对象是存储在一个内部类ThreadLocalMap的成员变量table里面的,定义如下:

static class ThreadLocalMap {

        /**
         * The entries in this hash map extend WeakReference, using
         * its main ref field as the key (which is always a
         * ThreadLocal object).  Note that null keys (i.e. entry.get()
         * == null) mean that the key is no longer referenced, so the
         * entry can be expunged from table.  Such entries are referred to
         * as "stale entries" in the code that follows.
         */
        static class Entry extends WeakReference<ThreadLocal<?>> {
            /** The value associated with this ThreadLocal. */
            Object value;

            Entry(ThreadLocal<?> k, Object v) {
                super(k);
                value = v;
            }
        }

        /**
         * The initial capacity -- MUST be a power of two.
         */
        private static final int INITIAL_CAPACITY = 16;

        /**
         * The table, resized as necessary.
         * table.length MUST always be a power of two.
         */
        private Entry[] table;
        ...
}

可以看到table是一个Entry类型的数组,Entry也是一个类,这个类里面又有一个成员变量Object类型的value,这就是ThreadLocal这个类存储值得地方。

典型使用场景

比较出名的一个应用场景是 Web服务器端的Session的存储。

Web容器采用线程隔离的多线程模型,也就是每一个请求都会对应一条线程,线程之间相互隔离,没有共享数据。这样能够简化编程模型,程序员可以用单线程的思维开发这种多线程应用。

当收到一个请求时,可以将当前Session信息存储在ThreadLocal中,在请求处理过程中可以随时使用Session信息,每个请求之间的Session信息互不影响。当请求处理完成后通过remove方法将当前Session信息清除即可。

猜你喜欢

转载自blog.csdn.net/topdeveloperr/article/details/82180653