ThreadLocal

1、ThreadLocal是什么?

顾名思义,线程级的本地变量,也就是线程之间是隔离的,不共享。适合不同线程存储各自的上下文。webapp中应用较多。

2、ThreadLocal中的属性和方法

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);
}

threadLocalHashCode在ThreadLocal实例化的时候就确定了,为什么hash增加值为0x61c88647可参考https://www.cnblogs.com/ilellen/p/4135266.html

initialValue

protected T initialValue() {
    return null;
}

返回初始化线程副本,默认返回null。这个方法是protected的,就是让调用者根据自己的业务逻辑去覆盖,编写自己的初始化逻辑

withInitial

public static <S> ThreadLocal<S> withInitial(Supplier<? extends S> supplier) {
    return new SuppliedThreadLocal<>(supplier);
}

static final class SuppliedThreadLocal<T> extends ThreadLocal<T> {

    private final Supplier<? extends T> supplier;

    SuppliedThreadLocal(Supplier<? extends T> supplier) {
        this.supplier = Objects.requireNonNull(supplier);
    }

    @Override
    protected T initialValue() {
        return supplier.get();
    }
}

//该接口不在ThreaLocal.java中
public interface Supplier<T> {

    /**
     * Gets a result.
     *
     * @return a result
     */
    T get();
}

传入一个Supplier的对象,覆盖其get方法,本质也是编写初始化逻辑。SuppliedThreadLocal是ThreadLocal的一个内部静态类,并且继承了ThreadLocal,覆盖了原来的initialValue()方法,调用supplier.get()返回。

为了研究接下来的几个方法,必须先研究ThreadLocal中的内部静态类ThreadLocalMap,因为后面的方法都和它息息相关。

ThreadLocalMap

static class ThreadLocalMap {
    static class Entry extends WeakReference<ThreadLocal<?>> {
        /** The value associated with this ThreadLocal. */
        Object value;
    
        Entry(ThreadLocal<?> k, Object v) {
            super(k);
            value = v;
        }
    }
    
    private static final int INITIAL_CAPACITY = 16;
    
    private Entry[] table;
    
    private int threshold; // Default to 0
}

初始化容量、门限、Entry数组这些都和HashMap类似。

注意Entry是继承弱引用的,弱引用ThreadLocal对象本身。由弱引用的特性可知,当ThreadLocal对象变成弱可及时(如在代码中显式地将ThreadLocal置null),GC会回清除掉该对象,这也是为什么Entry中用弱引用的原因。但是会有另外一个问题,ThreadLocal对象在仅弱可及时被清除掉了,但是当时一起传进来的value却还留在Entry数组中,因为一直有强引用的存在,没法被释放,所以有了内存泄露的风险。关于内存泄露的问题后面专门说明。

set

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

ThreadLocalMap getMap(Thread t) {
    return t.threadLocals;
}

private void set(ThreadLocal<?> key, Object value) {
    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();

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

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

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

//线性探测
private static int nextIndex(int i, int len) {
    return ((i + 1 < len) ? i + 1 : 0);
}

void createMap(Thread t, T firstValue) {
    t.threadLocals = new ThreadLocalMap(this, firstValue);
}

//Thread.java中的代码
ThreadLocal.ThreadLocalMap threadLocals = null;

1)获取当前线程的threadLocals

2)threadLocals如果为null,创建ThreadLocalMap对象,生成Entry数组赋给table,set进来的value放到对应的Entry中

3)threadLocals如果不为空,则根据hash值算出数组索引

4)如果索引所在Entry存放的ThreadLocal对象和本次插入的相同,更新value

5)如果索引所在Entry存放的ThreadLocal已经被清除了(弱引用),则替换失效节点

6)如果4和5都不是,则寻找下一个索引,ThreadLocal针对hash碰撞采用的线性探测法,而不是HashMap中的链表加红黑树的做法

7)直到找到某个Entry为null,将新的key和value放入到该位置

8)清除某些失效节点

其中replaceStaleEntry、cleanSomeSlots、expungeStaleEntry具体都做了什么,可以参考https://www.cnblogs.com/cfyrwang/p/8166369.html

get

public T get() {
    //1)
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null) {
        //3)
        ThreadLocalMap.Entry e = map.getEntry(this);
        if (e != null) {
            @SuppressWarnings("unchecked")
            T result = (T)e.value;
            return result;
        }
    }
    return setInitialValue();
}

ThreadLocalMap getMap(Thread t) {
    return t.threadLocals;
}

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);
}

private Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) {
    Entry[] tab = table;
    int len = tab.length;

    while (e != null) {
        ThreadLocal<?> k = e.get();
        if (k == key)
            return e;
        if (k == null)
            expungeStaleEntry(i);
        else
            i = nextIndex(i, len);
        e = tab[i];
    }
    return null;
}

//2)
private T setInitialValue() {
    T value = initialValue();
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null)
        map.set(this, value);
    else
        createMap(t, value);
    return value;
}

void createMap(Thread t, T firstValue) {
    t.threadLocals = new ThreadLocalMap(this, firstValue);
}

1)获取当前线程的threadLocals

2)threadLocals如果为null,则调用setInitialValue获取初始值(如果没有覆盖initialValue方法,则默认返回null),并创建线程的ThreadLocalMap对象

3)threadLocals如果不为null,说明当前线程已经存在过ThreadLocal对象了。调用getEntry获取TreadLocal所在的Entry,获取value

remove

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

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) {
            //2)
            e.clear();
            //3)
            expungeStaleEntry(i);
            return;
        }
    }
}

private int expungeStaleEntry(int staleSlot) {
    Entry[] tab = table;
    int len = tab.length;

    // expunge entry at staleSlot
    //4)
    tab[staleSlot].value = null;
    tab[staleSlot] = null;
    size--;

    // Rehash until we encounter null
    Entry e;
    int i;
    for (i = nextIndex(staleSlot, len);
         (e = tab[i]) != null;
         i = nextIndex(i, len)) {
        ThreadLocal<?> k = e.get();
        if (k == null) {
            e.value = null;
            tab[i] = null;
            size--;
        } else {
            int h = k.threadLocalHashCode & (len - 1);
            if (h != i) {
                tab[i] = 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;
}

//Reference.java中的代码
public void clear() {
    this.referent = null;
}

1)获取当前线程的threadLocals

2)找到对应的Entry节点,将引用的对象置null

3)清除失效的节点

4)重点就是将value置null,断开value的强引用,Entry置null,断开强引用

3、ThreadLocal结构

先来看个例子

public class ThreadLocalTest implements Runnable{
    private static ThreadLocal<Long> threadLocalLong = new ThreadLocal<>();
    private static ThreadLocal<String> threadLocalString = new ThreadLocal<String>() {
    @Override
    public String initialValue() {
        return "hello";
    }
};

@Override
public void run() {
    Long value = threadLocalLong.get();
    if (value == null) {
        System.out.println(Thread.currentThread().getName() + " threadLocalLong init value is null");
    }

    threadLocalLong.set(Thread.currentThread().getId());

    System.out.println(Thread.currentThread().getName() + " threadLocalLong value is " + threadLocalLong.get());

    threadLocalLong.remove();

    System.out.println(Thread.currentThread().getName() + " threadLocalLong value is " + threadLocalLong.get());

    String string = threadLocalString.get();
    System.out.println(Thread.currentThread().getName() + " threadLocalString init value is " + string);
}
    
    public static void main(String[] args) throws InterruptedException{
        for (int i = 0; i < 2; i++) {
            Thread thread = new Thread(new ThreadLocalTest());
            thread.start();  
        }
    }
}

输出为

Thread-1 threadLocalLong init value is null
Thread-1 threadLocalLong value is 14
Thread-1 threadLocalLong value is null
Thread-1 threadLocalString init value is hello
Thread-0 threadLocalLong init value is null
Thread-0 threadLocalLong value is 13
Thread-0 threadLocalLong value is null
Thread-0 threadLocalString init value is hello

结构图为

每个Thread维护自己的Map,里面存放各自线程的ThreadLocal对象,所以这也是为什么它能做到线程间相互隔离。

正是由于这种特性,所以ThreadLocal变量最好声明成private static的,如果你声明为成员变量,那么每new一个线程,就会多出一个ThreadLocal对象,而最终存储在各自线程的ThreadLocalMap中,声明为private static的可以避免生成多余的ThreadLocal对象。但是这样会把ThreadLocal的声明周期拉长,同类相同,可能会造成内存泄露。

4、内存泄露

前面说过,Entry的key是ThreadLocal对象的弱引用,当线程中把ThreadLocal对象的强引用断开后,如置null,那么ThreadLocal对象变成弱可及的,在下次GC时会被回收。Entry的key被回收了,但是value因为Entry的强引用关系,会一直得不到回收,造成内存泄露

网上看的一个图来说明:

其中实线为强引用,虚线为弱引用。

如果线程迟迟得不到回收,那么value一直就得不到回收,所以线程池中使用ThreadLocal就可能会造成内存泄露,还可能产生脏读。

remove方法中会调用expungeStaleEntry(set和get时也会对key为null的节点进行清除),将Entry节点及value的强引用断开,便于下次GC回收,所以在使用的时候,最后记得调用remove方法。如

try {
    threadLocal.set();
    threadLocal.get();
    ...
} finally {
    threadLocal.remove();
}

Netty中的FastThreadLocal就是这么做的。

 

参考:

https://www.cnblogs.com/ilellen/p/4135266.html

https://www.cnblogs.com/cfyrwang/p/8166369.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值