Java多线程-ThreadLocal解析

ThreadLocal是一个本地线程副本变量工具类,该变量的作用域为当前线程。每个线程都有自己的ThreadLocal,且它们是相互隔离的。这样可以用来避免资源竞争带来的多线程问题。

ThreadLocalMap

ThreadLocalMap是ThreadLocal中的静态内部类,我们先对ThreadLocalMap进行分析,以便于我们更好的理解ThreadLocal的操作原理。

ThreadLocalMap是一个存储键值对的数组集合,存储键值对的类为ThreadLocalMap的静态内部类Entry,Entry数组集合为ThreadLocalMap的属性table。

Entry
/**
 * 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;
    }
}

从Entry类源码可以知道,键值对的键为泛型ThreadLocal的弱引用。

属性
    /**
     * ThreadLocalMap的初始容量,必须为2的幂
     */
    private static final int INITIAL_CAPACITY = 16;

    /**
     * 键值对数组
     */
    private Entry[] table;

    /**
     * 数组大小
     */
    private int size = 0;

    /**
     * 扩容阈值
     */
    private int threshold; // Default to 0
构造方法
/**
 * 根据需要保存的键值对创建ThreadLocalMap对象
 */
ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
    table = new Entry[INITIAL_CAPACITY];
    // 获取ThreadLocal实例的hash值,并计算目标索引
    int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
    // 存储新的键值对
    table[i] = new Entry(firstKey, firstValue);
    size = 1;
    // 更新扩容阈值
    setThreshold(INITIAL_CAPACITY);
}
void set(ThreadLocal<?> key, Object value)

该方法实现向ThreadLocalMap中添加新的Entry。

/**
 * 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;
    // 通过key获取新元素的目标索引
    int i = key.threadLocalHashCode & (len-1);

    // 循环遍历数组
    for (Entry e = tab[i];
         e != null;
         e = tab[i = nextIndex(i, len)]) {
        ThreadLocal<?> k = e.get();
		
        // k相等,即同一个ThreadLocal实例,则覆盖值
        if (k == key) {
            e.value = value;
            return;
        }
		// 如果key不存在,则替换
        if (k == null) {
            replaceStaleEntry(key, value, i);
            return;
        }
    }
	
    tab[i] = new Entry(key, value);
    int sz = ++size;
    if (!cleanSomeSlots(i, sz) && sz >= threshold)
        rehash();
}

set方法添加新值比较简单:通过k获得相应的目标索引,检查目标所以索引位置的数据,最后将要添加的键值对包装成Entry放入目标位置。

从上述代码也可以看出ThreadLocalMap解决hash冲突是通过线性探测来实现的

Entry getEntry(ThreadLocal<?> key)

该方法通过ThreadLocal实例,从ThreadLocalMap中获得相应的Entry

/**
 * Get the entry associated with key.  This method
 * itself handles only the fast path: a direct hit of existing
 * key. It otherwise relays to getEntryAfterMiss.  This is
 * designed to maximize performance for direct hits, in part
 * by making this method readily inlinable.
 *
 * @param  key the thread local object
 * @return the entry associated with key, or null if no such
 */
private Entry getEntry(ThreadLocal<?> key) {
    // 通过ThreadLocal获得目标索引
    int i = key.threadLocalHashCode & (table.length - 1);
    // 通过目标索引从Entry数组中获得相应的Entry
    Entry e = table[i];
    // 返回Entry
    if (e != null && e.get() == key)
        return e;
    else
        return getEntryAfterMiss(key, i, e);
}
void remove(ThreadLocal<?> key)

该方法通过ThreadLocal实例,从ThreadLocalMap中移除相应的Entry

/**
 * 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;
        }
    }
}
void resize()

ThreadLocalMap的扩容方法,按照2倍长度扩容。并且还会标记垃圾值,方便GC回收。

/**
 * Double the capacity of the table.
 */
private void resize() {
	Entry[] oldTab = table;
	int oldLen = oldTab.length;
	int newLen = oldLen * 2;
	// 新建一个数组,按照2倍长度扩容
	Entry[] newTab = new Entry[newLen];
	int count = 0;

	// 将旧数组的值拷贝到新数组上
	for (int j = 0; j < oldLen; ++j) {
		Entry e = oldTab[j];
		if (e != null) {
			ThreadLocal<?> k = e.get();
			// 若有垃圾值,则标记清理该元素的引用,以便GC回收
			if (k == null) {
				e.value = null;
			} else {
				// 计算 ThreadLocal 在新数组中的位置
				int h = k.threadLocalHashCode & (newLen - 1);
				// 如果发生冲突,使用线性探测往后寻找合适的位置
				while (newTab[h] != null) {
					h = nextIndex(h, newLen);
				}
				newTab[h] = e;
				count++;
			}
		}
	}
	// 设置新的扩容阈值,为数组长度的三分之二
	setThreshold(newLen);
	size = count;
	table = newTab;
}

ThreadLocal

构造方法

ThreadLocal的构造其实什么也没做

/**
 * Creates a thread local variable.
 * @see #withInitial(java.util.function.Supplier)
 */
public ThreadLocal() {
}
void set(T value)

通过set方法可以将某一变量的副本放入当前线程的ThreadLocal中,具体见源码注释。

/**
 * Sets the current thread's copy of this thread-local variable
 * to the specified value.  Most subclasses will have no need to
 * override this method, relying solely on the {@link #initialValue}
 * method to set the values of thread-locals.
 *
 * @param value the value to be stored in the current thread's copy of
 *        this thread-local.
 */
public void set(T value) {
    // 获取当前线程
    Thread t = Thread.currentThread();
    // 根据当前线程获取ThreadLocalMap
    ThreadLocalMap map = getMap(t);
    if (map != null)
        // ThreadLocalMap不为空,直接添加新的键值对
        map.set(this, value);
    else
        // ThreadLocalMap为空,创建并设置
        createMap(t, value);
}

getMap方法是获取当前线程对象的ThreadLocalMap对象。

/**
 * Get the map associated with a ThreadLocal. Overridden in
 * InheritableThreadLocal.
 *
 * @param  t the current thread
 * @return the map
 */
ThreadLocalMap getMap(Thread t) {
    return t.threadLocals;
}
public
class Thread implements Runnable {
 
    /* ThreadLocal values pertaining to this thread. This map is maintained
     * by the ThreadLocal class. */
    ThreadLocal.ThreadLocalMap threadLocals = null;
    
    ...
}

每一个Thread实例维护一个ThreadLocalMap,该属性默认为null。ThreadLocalMap类是ThreadLocal类中的静态类部类,在上面我们已经简单分析过了。

void createMap(Thread t, T firstValue)
/**
 * Create the map associated with a ThreadLocal. Overridden in
 * InheritableThreadLocal.
 *
 * @param t the current thread
 * @param firstValue value for the initial entry of the map
 */
void createMap(Thread t, T firstValue) {
    // 通过当前ThreadLocal实例和set的值初始化一个ThreadLocalMap,并保存到当前线程实例
    t.threadLocals = new ThreadLocalMap(this, firstValue);
}

综上,ThreadLocal#set方法的流程:

  • 获取当前线程实例
  • 从当前线程实例获取ThreadLocalMap实例,ThreadLocalMap是一个存储键值对的数组,键为ThreadLocal的弱引用,值为通过ThreadLocal#set传入的变量
  • 判断该ThreadLocalMap属性实例是否为null,在根据相应的策略将数据保存到ThreadLocalMap中
    • 当ThreadLocalMap为null:用当前ThreadLocal和需要保存的变量初始化一个ThreadLocalMap,并将该ThreadLocalMap实例保存到当前线程
    • 当ThreadLocalMap不为null:说明当前线程的ThreadLocalMap已被初始化,直接调用ThreadLocalMap#set传入当前ThreadLocal实例和需要保存的变量
T 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
    ThreadLocalMap map = getMap(t);
    if (map != null) {
        // 通过当前ThreadLocal实例获得Entry
        ThreadLocalMap.Entry e = map.getEntry(this);
        if (e != null) {
            @SuppressWarnings("unchecked")
            // 在通过Entry获得其中的变量
            T result = (T)e.value;
            return result;
        }
    }
    // 如果ThreadLocalMap为null,则初始化一个,保存的变量为null,返回也就为null
    return setInitialValue();
}

从ThreadLocalMap中获取值的方式和Map区别不大,就是不需要指定k,因为k就是当前调用get方法的ThreadLocal实例,通过该实例从ThreadLocalMap中获得Entry,再从Entry中获得保存的变量。但如果ThreadLocalMap为null,则会使用当前ThreadLocal实例和null初始化一个ThreadLocalMap,当然返回值肯定为null。

void remove()
/**
 * Removes the current thread's value for this thread-local
 * variable.  If this thread-local variable is subsequently
 * {@linkplain #get read} by the current thread, its value will be
 * reinitialized by invoking its {@link #initialValue} method,
 * unless its value is {@linkplain #set set} by the current thread
 * in the interim.  This may result in multiple invocations of the
 * {@code initialValue} method in the current thread.
 *
 * @since 1.5
 */
 public void remove() {
     ThreadLocalMap m = getMap(Thread.currentThread());
     if (m != null)
         m.remove(this);
 }

综上,我们分析了ThreadLocal和ThreadLocalMap中的几个方法

ThreadLocalThreadLocalMap
public void set(T value)private void set(ThreadLocal<?> key, Object value)
public T get()private Entry getEntry(ThreadLocal<?> key)
public void remove()private void remove(ThreadLocal<?> key)

可以看到我们操作ThreadLocal,实际上是操作ThreadLocal中的静态内部类ThreadLocalMap,而且对ThreadLocalMap的操作都是通过其调用者ThreadLocal来实现的。ThreadLocalMap就是一个键值对数组的Map结构,其中键值对Entry有一个特点就是:它的键是当前ThreadLocal的弱引用。

下面是Thread、ThreadLocal、ThreadLocalMap三者之间的关系:

在这里插å¥å›¾ç‰‡æè¿°

弱引用

Java中有四大引用类型,分别为:

  • 强引用:强引用是使用最普遍的引用,即直接用new关键字创建对象的引用。如果一个对象具有强引用,那垃圾回收器绝不会回收它。当内存空间不足,Java虚拟机宁愿抛出OutOfMemoryError错误,使程序异常终止,也不会靠随意回收具有强引用的对象来解决内存不足的问题。
  • 软引用:一个对象只具有软引用时,如果内存空间足够,垃圾回收器就不会回收它;如果内存空间不足,就会回收这些具有软引用的对象的内存。只要垃圾回收器没有回收它,该对象就可以被程序使用。软引用可用来实现内存敏感的高速缓存。
    软引用可以和一个引用队列(ReferenceQueue)联合使用,如果软引用所引用的对象被垃圾回收器回收,Java虚拟机就会把这个软引用加入到与之关联的引用队列中。
  • 弱引用:弱引用与软引用的区别在于:只具有弱引用的对象拥有更短暂的生命周期。在垃圾回收器线程扫描它所管辖的内存区域的过程中,一旦发现了只具有弱引用的对象,不管当前内存空间足够与否,都会回收它的内存。不过,由于垃圾回收器是一个优先级很低的线程,因此不一定会很快发现那些只具有弱引用的对象。
    弱引用可以和一个引用队列(ReferenceQueue)联合使用,如果弱引用所引用的对象被垃圾回收,Java虚拟机就会把这个弱引用加入到与之关联的引用队列中。
  • 虚引用:虚引用”顾名思义,就是形同虚设,与其他几种引用都不同,虚引用并不会决定对象的生命周期。如果一个对象仅持有虚引用,那么它就和没有任何引用一样,在任何时候都可能被垃圾回收器回收。
    虚引用主要用来跟踪对象被垃圾回收器回收的活动。虚引用与软引用和弱引用的一个区别在于:虚引用必须和引用队列 (ReferenceQueue)联合使用。当垃圾回收器准备回收一个对象时,如果发现它还有虚引用,就会在回收对象的内存之前,把这个虚引用加入到与之 关联的引用队列中。

ThreadLocal的内存泄漏

为什么ThreadLocal作为ThreadLocalMap的key要使用弱引用呢?

若是强引用,也就是上图的虚线变成强引用的实线指向,即使在外部把ThreadLocal实例置为null(只是断开引用),但ThreadLocalMap中的key指向ThreadLocal实例的引用并没有改变(根据可达性分析,存在引用链Thread->ThreadLocalMap->Entry->key。该ThreadLocal实例存在强引用,不可被回收)。所以该ThreadLocal并不会被GC回收,从而造成内存泄漏。

而使用弱引用,当把ThreadLocal实例置为null,没有任何强引用指向ThreadLocal实例,所以ThreadLocal就能顺利被GC回收。

综上,ThreadLocalMap使用弱引用是用来解决ThreadLocal实例作为key存在的内存泄漏问题。

纵使这样,ThreadLocal依旧还存在内存泄漏问题:ThreadLocalMap的key被垃圾回收了,但value的强引用依然存在,即存在引用链:Thread->ThreadLocalMap->Entry->value,所以依然存在value的内存泄漏。

理解帮助
  • 参数传递分为值传递和引用传递。值传递是对于基本类型的变量,传递的是值的副本;而引用传递也是传递的引用的副本,只不过这些引用都指向同一个对象,都可以操作这个对象。断开一个引用,对其他引用不会产生影响。
  • 可达性分析算法是GC的垃圾判定算法,在以后的博文中会有详细介绍分析。
  • 内存泄漏:是指在申请内存后,无法释放已经申请的内存空间,一次内存泄漏危害可以忽略,但如果任其法阵最终会导致内存溢出。

其实本质上产生内存泄漏问题的原因是因为ThreadLocalMap是作为Thread的属性,只要当前线程一直存活,ThreadLocalMap、Entry、key、value就不会被GC。如果ThreadLocal应用在线程池中,线程池中的线程都是服用的,那么导致的内存泄漏就更加严重。

解决方案

在使用完ThreadLocal之后,调用remove方法,使存在内存泄漏的引用释放掉就解决了内存泄漏问题。其本质上也是执行ThreadLocalMap#remove。

JDK建议将ThreadLocal定义为private static。

ThreadLocalMap#remove
/**
 * 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;
        }
    }
}
Reference#clear

释放弱引用

/**
 * Clears this reference object.  Invoking this method will not cause this
 * object to be enqueued.
 *
 * <p> This method is invoked only by Java code; when the garbage collector
 * clears references it does so directly, without invoking this method.
 */
public void clear() {
    this.referent = null;
}
ThreadLocalMap#expungeStaleEntry

释放value、Entry的引用,并进行重hash

/**
 * Expunge a stale entry by rehashing any possibly colliding entries
 * lying between staleSlot and the next null slot.  This also expunges
 * any other stale entries encountered before the trailing null.  See
 * Knuth, Section 6.4
 *
 * @param staleSlot index of slot known to have null key
 * @return the index of the next null slot after staleSlot
 * (all between staleSlot and this slot will have been checked
 * for expunging).
 */
private int expungeStaleEntry(int staleSlot) {
    Entry[] tab = table;
    int len = tab.length;

    // expunge entry at staleSlot
    // 释放value的引用
    tab[staleSlot].value = null;
    // 释放Entry的引用
    tab[staleSlot] = null;
    size--;

    // Rehash until we encounter null
    // 重新hash
    Entry e;
    int i;
	...
    return i;
}

调用remove方法,可以将key、value、Entry的引用释放掉,从而解决ThreadLocal的内存泄漏问题。Java为了最小化减少内存泄漏的可能性和影响,在ThreadLocal的set、get的时候都会清楚ThreadLocalMap里的所有key为null的value。

ThreadLocal应用

  • 保存线程独享的对象

  • 在线程内部传递数据

具体应用:

  • DbUtils对数据库连接的处理

  • MyBatis关于分页处理

  • Spring关于Transaction的处理

  • 解决SimpleDataFormat日期解析问题

总结

  • ThreadLocal实现对对象实现线程之间的隔离,线程独享对象,用来解决多线程的并发访问。
  • 通过ThreadLocal保存的对象是存储在ThreadLocal的类部类ThreadLoMap中,以当前ThreadLocal实例的弱引用为key,保存的对象为value,两者包装成一个Entry,Entry继承WeakReference<ThreadLocal<?>>。ThreadLocalMap的数据结构是数组,ThreadLocalMap是存在Thread类中的属性,每一个线程维护一个ThreadLocalMap。
  • ThreadLocal存在key和value的内存泄漏问题,需在使用完ThreadLocal后调用其remove方法释放引用。虚引用是用来解决key的内存泄漏问题。

使用ThreadLocal的好处

  • 达到线程安全的目的
  • 不需要加锁,执行效率高
  • 免去传参的繁琐,降低代码耦合度

ThreadLocal也是解决多线程资源同步问题的除开加锁的另一种方案。

ThreadLocal和synchronized的区别

相同点:ThreadLocal和线程同步机制都是为了解决多线程中相同变量的访问冲突问题。

区 别:

  • Synchronized是通过线程等待,以互斥的方式,牺牲时间来解决访问冲突。

  • ThreadLocal是通过每个线程单独一份存储空间,牺牲空间来解决冲突,并且相比于Synchronized,ThreadLocal具有线程隔离的效果,只有在线程内才能获取到对应的值,线程外则不能访问到想要的值。

优先使用框架的支持,而不是自己创造

例如在Spring框架中,如果可以使用RequestContextHolder,那么就不需要自己维护ThreadLocal,因为自己可能会忘记调用remove()方法等,造成内存泄漏。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值