文章目录

  • 一、ThreadLocal简单使用
  • 二、ThreadLocal源码详解
  • 1、set方法
  • (1)getMap(t)
  • (2)createMap
  • 2、get方法
  • 3、setInitialValue方法
  • 三、ThreadLocalMap详解
  • 1、ThreadLocalMap为什么要设置Entry数组
  • 2、key计算的下标会重复吗?
  • 3、Entry
  • 4、getEntry方法
  • 5、set方法
  • (1)线性探测
  • (2)replaceStaleEntry
  • 6、ThreadLocal 内存泄露的原因
  • 7、线程池中ThreadLocal未remove问题


一、ThreadLocal简单使用

注!本文不介绍ThreadLocal的基础使用,主要以源码解析为主。

ThreadLocal实际上一种线程隔离机制,也是为了保证在多线程环境下对于共享变量的访问的安全性。

public class ThreadLocalDemo {

//    private static int num=0; // 线程共享

	// 线程隔离
    static ThreadLocal<Integer> local=new ThreadLocal<Integer>(){
        protected Integer initialValue(){
            return 0; //初始化一个值
        }
    };

    public static void main(String[] args) {
        Thread[] thread=new Thread[5];
        for (int i=0;i<5;i++){
            thread[i]=new Thread(()->{
                int num=local.get(); //获得的值都是0
                local.set(num+=5); //设置到local中  thread[0] ->thread[1] ->
                System.out.println(Thread.currentThread().getName()+"-"+num); // 都是5
                local.remove(); // 用完一定要remove,否则会内存泄漏
            });
        }
        for (int i = 0; i < 5; i++) {
            thread[i].start();
        }
    }
}

二、ThreadLocal源码详解

ThreadLocal定义了几个关键的方法,包含初始化方法、get、set和remove方法。

ThreadLocal源码深度详解_数组

1、set方法

// java.lang.ThreadLocal#set
public void set(T value) {
	// 获得当前线程
    Thread t = Thread.currentThread();
    // 从Thread中获取ThreadLocalMap 
    ThreadLocalMap map = getMap(t);
    if (map != null)
    	// 如果map不为空,就设置值
        map.set(this, value);
    else
        // 如果map为空,就创建Map,第一次调用set时,map肯定是空的
        createMap(t, value);
}

(1)getMap(t)

我们发现getMap方法,其实是从Thread中获取一个ThreadLocalMap,也就是说,线程的ThreadLocalMap其实是定义在Thread内部的,这就意味着每一个线程都包含着一个ThreadLocalMap ,这也就是ThreadLocal为什么可以实现线程隔离,因为每一个线程都保存了一个ThreadLocalMap的副本。

// java.lang.ThreadLocal#getMap
ThreadLocalMap getMap(Thread t) {
    return t.threadLocals;
}

(2)createMap

创建Map,并将初始化数据传递进去

// java.lang.ThreadLocal#createMap
void createMap(Thread t, T firstValue) {
    t.threadLocals = new ThreadLocalMap(this, firstValue);
}

2、get方法

// java.lang.ThreadLocal#get
public T get() {
	// 拿到当前线程
    Thread t = Thread.currentThread();
    // 从Thread中获取ThreadLocalMap 
    ThreadLocalMap map = getMap(t);
    if (map != null) {
    	// 如果map不为空,直接获取到ThreadLocalMap中存的Entry,然后获取value值
        ThreadLocalMap.Entry e = map.getEntry(this);
        if (e != null) {
            @SuppressWarnings("unchecked")
            T result = (T)e.value;
            return result;
        }
    }
    // 如果map为空,会执行ThreadLocal的初始化逻辑
    return setInitialValue();
}

3、setInitialValue方法

我们文章刚开始写的,定义ThreadLocal时定义一个匿名内部类,重写initialValue,这相当于是一个懒加载的过程,调用get方法时,如果没有设置过值,就会触发初始化过程;而调用set方法本身就是设置值,就算有默认值也会被覆盖,所以不会触发初始化方法。

private T setInitialValue() {
	// 可以被子类重写的初始化方法,返回一个value
    T value = initialValue();
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null)
        map.set(this, value);
    else
        createMap(t, value);
    return value;
}

protected T initialValue() {
    return null;
}

三、ThreadLocalMap详解

ThreadLocalMap包含一个构造方法,构造方法创建ThreadLocalMap的同时,会将首次初始化的key和value存入。

// java.lang.ThreadLocal.ThreadLocalMap#ThreadLocalMap(java.lang.ThreadLocal<?>, java.lang.Object)
ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
    table = new Entry[INITIAL_CAPACITY]; // 初始化因子为16,创建一个Entry的数组(并不意味着只能16个)
    int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1); // 计算下标,firstkey传过来的是ThreadLocal对象,所以计算的下标都是相同的
    table[i] = new Entry(firstKey, firstValue); // 创建Entry,firstkey就是当前的threadLocal,value就是我们设置的值
    size = 1;
    setThreshold(INITIAL_CAPACITY);
}

如下图,也就意味着,ThreadLocalMap中保存的数据结构大致是这样子的(key因为是同一个ThreadLocal,也就意味着相同的下标):

ThreadLocal源码深度详解_开发语言_02

1、ThreadLocalMap为什么要设置Entry数组

可能有小伙伴疑问了,既然firstkey传的都是一个ThreadLocal,为什么还要创建一个Entry数组呢?同一个ThreadLocal每次生成的下标肯定是相同的啊,剩下的几个下标用来做什么?

这里的key以ThreadLocal的hash作为下标,并生成一个数组,目的是为了支持一个线程中可以设置多个ThreadLocal:

static ThreadLocal<Integer> local=new ThreadLocal<Integer>(){
    protected Integer initialValue(){
        return 0; //初始化一个值
    }
};
static ThreadLocal<Integer> local1=new ThreadLocal<Integer>(){
    protected Integer initialValue(){
        return 0; //初始化一个值
    }
};

注意!虽然创建的table默认的因子是16,这并不意味着一个只能使用16个ThreadLocal,是可以自动扩容的(与Map机制不同)。

ThreadLocal源码深度详解_初始化_03

2、key计算的下标会重复吗?

// firstKey调用threadLocalHashCode 与上INITIAL_CAPACITY - 1 也就是15
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);

private final int threadLocalHashCode = nextHashCode();

private static AtomicInteger nextHashCode = new AtomicInteger();
private static final int HASH_INCREMENT = 0x61c88647;
private static int nextHashCode() {
    return nextHashCode.getAndAdd(HASH_INCREMENT);
}

这里是使用一个魔数,相当于一个黄金分割的数字,通过斐波那契数列来生成hash,什么意思呢?
我们使用下面的demo解释一下,使用0x61c88647这个黄金分割的数字,生成的下一个值,均衡的生成一个散列,并不会重复。

public class HashDemo {

    private static final int HASH_INCREMENT = 0x61c88647;

    public static void main(String[] args) {
        magicHash(16);
        magicHash(32);
    }

    private  static void magicHash(int size){
        int hashCode=0;
        for(int i=0;i<size;i++){
            hashCode=i * HASH_INCREMENT+HASH_INCREMENT;
            System.out.print((hashCode&(size-1))+"  ");
        }
        System.out.println("");
        // 7  14  5  12  3  10  1  8  15  6  13  4  11  2  9  0
        //7  14  21  28  3  10  17  24  31  6  13  20  27  2  9  16  23  30  5  12  19  26  1  8  15  22  29  4  11  18  25  0
    }
}

3、Entry

Entry中保存着key和value值,我们可以发现,key是使用WeakReference弱引用,而value是强引用。

java强引用、软引用、弱引用、虚引用-Java的引用类型总共有四种,你都知道吗

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

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

4、getEntry方法

从ThreadLocalmap中获取Entry。

// java.lang.ThreadLocal.ThreadLocalMap#getEntry
private Entry getEntry(ThreadLocal<?> key) {
	// 获取下标
    int i = key.threadLocalHashCode & (table.length - 1);
    // 直接从数组中根据下标获取
    Entry e = table[i];
    if (e != null && e.get() == key)
        return e;
    else
        return getEntryAfterMiss(key, i, e);
}

5、set方法

set方法通过key和value来存放数据(区别于Map),这里的key就是ThreadLocal。

// java.lang.ThreadLocal.ThreadLocalMap#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);
	// 线性探测(开放寻址,hashmap是链式寻址方式)解决冲突
    for (Entry e = tab[i];
         e != null;
         // 从i的位置往下探索
         e = tab[i = nextIndex(i, len)]) {
        ThreadLocal<?> k = e.get();

        if (k == key) { // 正常情况,直接查找到,直接修改值
            e.value = value;
            return;
        }

        if (k == null) { // 如果key为null,并且e不为null(for循环的条件),意味着ThreadLocal对象(key为弱引用)被回收了
        	// 替换脏的Entry,这也是尽可能避免内存泄漏问题
            replaceStaleEntry(key, value, i);
            return;
        }
    }
	// 如果key不存在,新建key
    tab[i] = new Entry(key, value);
    int sz = ++size;
    // 如果size超过阈值,会进行rehash
    if (!cleanSomeSlots(i, sz) && sz >= threshold)
        rehash();
}

(1)线性探测

ThreadLocalMap区别于Map,HashMap是使用拉链法进行解决hash冲突的,而ThreadLocalMap使用线性探测的方式解决冲突的:
算法-hash散列表查找详解

简单来说,写入时冲突 , 找到发生冲突最近的空闲单元;查找时, 从发生冲突的位置,往后查找。

线性探测,是用来解决hash冲突的一种策略。它是一种开放寻址策略,
我想大家应该都知道hash表,它是根据key进行直接访问的数据结构,也就是说我们可以通过hash函数把key映射到hash表中的一个位置来访问记录,从而加快查找的速度。存放记录的数据就是hash表(散列表)
当我们针对一个key通过hash函数计算产生的一个位置,在hash表中已经被另外一个键值对占用时,那么线性探测就可以解决这个冲突,这里分两种情况。
写入: 查找hash表中离冲突单元最近的空闲单元,把新的键值插入到这个空闲单元
查找: 根据hash函数计算的一个位置处开始往后查找,指导找到与key对应的value或者找到空的单元。

(2)replaceStaleEntry

这个方法的主要目的是,将key为null,但是value不为null的数组中的值替换为新的,一定程度上能解决内存泄漏问题。

// java.lang.ThreadLocal.ThreadLocalMap#replaceStaleEntry
private void replaceStaleEntry(ThreadLocal<?> key, Object value,
                               int staleSlot) {
    Entry[] tab = table;
    int len = tab.length;
    Entry e;

    // Back up to check for prior stale entry in current run.
    // We clean out whole runs at a time to avoid continual
    // incremental rehashing due to garbage collector freeing
    // up refs in bunches (i.e., whenever the collector runs).
    int slotToExpunge = staleSlot;
     // 向前查找,查找一个key为null的下标(当前key为空的话,它认为附近的key也大概率也有空的)
    for (int i = prevIndex(staleSlot, len);
         (e = tab[i]) != null;
         i = prevIndex(i, len))
        if (e.get() == null)
        	//通过循环遍历,可以定位到最前面一个无效的slot
        	// 改变下标位置
            slotToExpunge = i;

    // Find either the key or trailing null slot of run, whichever
    // occurs first
   	//从i开始往后一直遍历到数组最后一个Entry(线性探索)
    for (int i = nextIndex(staleSlot, len);
         (e = tab[i]) != null;
         i = nextIndex(i, len)) {
        ThreadLocal<?> k = e.get();

        // If we find key, then we need to swap it
        // with the stale entry to maintain hash table order.
        // The newly stale slot, or any other stale slot
        // encountered above it, can then be sent to expungeStaleEntry
        // to remove or rehash all of the other entries in run.
        if (k == key) { // 如果查找到我们的key了,直接替换value
            e.value = value;;//更新对应slot的value值
			//与无效的sloat进行交换
            tab[i] = tab[staleSlot];
            tab[staleSlot] = e;

            // Start expunge at preceding stale entry if it exists
            //如果最早的一个无效的slot和当前的staleSlot相等,则从i作为清理的起点
            if (slotToExpunge == staleSlot)
                slotToExpunge = i;
            //从slotToExpunge开始做一次连续的清理
            cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
            return;
        }

        // If we didn't find stale entry on backward scan, the
        // first stale entry seen while scanning for key is the
        // first still present in the run.
        //如果当前的slot已经无效,并且向前扫描过程中没有无效slot,则更新slotToExpunge为当前位置
        if (k == null && slotToExpunge == staleSlot)
            slotToExpunge = i;
    }

    // If key not found, put new entry in stale slot
    //如果key对应的value在entry中不存在,则直接放一个新的entry
    tab[staleSlot].value = null;
    tab[staleSlot] = new Entry(key, value);

    // If there are any other stale entries in run, expunge them
    //如果有任何一个无效的slot,则做一次清理
    if (slotToExpunge != staleSlot)
        cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
}

ThreadLocal源码深度详解_开发语言_04


ThreadLocal源码深度详解_初始化_05

6、ThreadLocal 内存泄露的原因

上面我们分析道,ThreadLocalMap中Entry中key是用弱引用保存的,触发垃圾回收后会直接回收掉。
而value是一个强引用,除非线程结束之后,触发垃圾回收才会被回收。实际上我们线程都会使用线程池来维护,使用ThreadLocal场景都是采用线程池,而线程池中的线程都是复用的,这样就可能导致非常多的entry(null,value)出现,从而导致内存泄露。

而只要在ThreadLocal使用完,调用其 remove 方法删除对应的 Entry ,就能避免内存泄漏。

ThreadLocal源码深度详解_开发语言_06

7、线程池中ThreadLocal未remove问题

线程池中的核心线程都是复用的,通过下面的实例,上一个任务的ThreadLocal如果没有remove,下一个任务会拿到上一个任务的数据,抛开内存泄漏不说,这是一个非常危险的操作!

所以,ThreadLocal用完之后remove,是一个很好的习惯!

其实

public class ThreadLocalDemo {
    // 三个线程的线程池,超过3个线程会放在缓冲区
    private static ExecutorService executorService = Executors.newFixedThreadPool(3);

    static ThreadLocal<Integer> local=new ThreadLocal<Integer>(){
        protected Integer initialValue(){
            return 0; //初始化一个值
        }
    };

    public static void main(String[] args) {

        Thread[] thread=new Thread[5];
        for (int i=0;i<5;i++){
            thread[i]=new Thread(()->{
                int num=local.get(); //获得的值都是0
                local.set(num+=5); //设置到local中  thread[0] ->thread[1] ->
                System.out.println(Thread.currentThread().getName()+"-"+num); // 都是5
                // local.remove(); // 用完一定要remove
            });
        }
        for (int i = 0; i < 5; i++) {
            executorService.execute(thread[i]);
        }
    }
}

// 执行结果
pool-1-thread-1-5
pool-1-thread-3-5
pool-1-thread-2-5
pool-1-thread-1-10
pool-1-thread-2-10