走进ThreadLocal

83 阅读5分钟

查看transaction事务代码的时候 发现TransactionSynchronizationManager类中存在一些这样的属性,于是看看ThreadLocal这个类

public abstract class TransactionSynchronizationManager {
    private static final ThreadLocal<Map<Object, Object>> resources = new NamedThreadLocal("Transactional resources");
    private static final ThreadLocal<Set<TransactionSynchronization>> synchronizations = new NamedThreadLocal("Transaction synchronizations");
    private static final ThreadLocal<String> currentTransactionName = new NamedThreadLocal("Current transaction name");
    private static final ThreadLocal<Boolean> currentTransactionReadOnly = new NamedThreadLocal("Current transaction read-only status");
    private static final ThreadLocal<Integer> currentTransactionIsolationLevel = new NamedThreadLocal("Current transaction isolation level");
    private static final ThreadLocal<Boolean> actualTransactionActive = new NamedThreadLocal("Actual transaction active");
}

1.ThreadLocal是什么

顾名思义:thread是线程,local是本地的意思。也就是线程本地的变量,ThreadLocal是属于当前线程的变量,线程之间是隔离的。因为不是线程之间共享的变量,所以是线程安全的。

Thread中有这样一个属性threadLocals,用来存放ThreadLocal和相应的value

public class Thread implements Runnable {
    ThreadLocal.ThreadLocalMap threadLocals = null;
......
}

//ThreadLocalMap为ThreadLocal的静态内部类
public class ThreadLocal<T> {

    static class ThreadLocalMap {
        //Entry为ThreadLocalMap的静态内部类,真正存放ThreadLocal和value的地方
        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;
    
    //ThreadLocalMap存储Entry数组
    private Entry[] table;
   
    ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
        //数组初始大小为16
        table = new Entry[INITIAL_CAPACITY];
        int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
        table[i] = new Entry(firstKey, firstValue);
        size = 1;
        //之后用来扩容
        setThreshold(INITIAL_CAPACITY);
    }
}

2.ThreadLocal中的方法

1.ThreadLocal中的set()方法

  • 1.取当前线程中threadLocals属性,即存放值的ThreadLocalMap

  • 2.1 线程中的map非null,存储当前ThreadLocal的引用和对应的值

  • 2.2 线程中的map为null,创建map,再存值

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中的set方法
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();
        //如果当前位置的key和要插入的相等,则覆盖原值
        if (k == key) {
            e.value = value;
            return;
        }
        if (k == null) {
            //1.查找是否存在当前key
            //2.1存在则覆盖该值,并且和在他前边key为null的entry交换位置
            //2.2不存在,则将key为null的entry进行覆盖
            //3.清除key为null的entry
            replaceStaleEntry(key, value, i);
            return;
        }
    }

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


//ThreadLocal.set()->createMap()  set()方法中的createMap()方法
void createMap(Thread t, T firstValue) {
    t.threadLocals = new ThreadLocalMap(this, firstValue);
}

2.ThreadLocal中的get()方法

  • 1.取当前线程中threadLocals属性,即存放值的ThreadLocalMap

  • 2.1 线程中的map非null,获取map中的entry

    entry非null,取值返回

  • 2.2 否则,返回null

public T get() {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null) {
        //存在key为null的entry置为null
        ThreadLocalMap.Entry e = map.getEntry(this);
        if (e != null) {
            @SuppressWarnings("unchecked")
            T result = (T)e.value;
            return result;
        }
    }
    return setInitialValue();
}

//get()->getEntry()  get()方法中引用的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);
}

//getEntry()->getEntryAfterMiss()  get()方法中引用的getEntryAfterMiss()方法
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;
}

//get()->setInitialValue()  get()方法中引用的setInitialValue()方法
//在map中存放(this,null)的entry
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;
}

3.ThreadLocal中的remove()方法

public void remove() {
    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) {
            //将entry中的key置为null
            e.clear();
            expungeStaleEntry(i);
            return;
        }
    }
}

4.上面几个方法中都引用的方法expungeStaleEntry()

  • 1 将staleSlot位置的entry和其value置为null
  • 2.1 从下一个节点开始遍历,如果key为null,则将其entry和其value置为null
  • 2.2 如果key不为null,则对当前的key取hash值,判断当前的位置和hash出来的值是否一样
  • 2.2.1 如果值一样,则继续遍历下一个entry不为null的节点
  • 2.2.2 如果值不一样,从hash出来的位置开始遍历,放到第一个为null的entry中
private int expungeStaleEntry(int staleSlot) {
    Entry[] tab = table;
    int len = tab.length;

    // 将key为null的entry置为null
    tab[staleSlot].value = null;
    tab[staleSlot] = null;
    size--;

    Entry e;
    int i;
    //从下一个结点开始找key为null的entry
    for (i = nextIndex(staleSlot, len);
         (e = tab[i]) != null;
         i = nextIndex(i, len)) {
        ThreadLocal<?> k = e.get();
        //key为null,将entry置为null
        if (k == null) {
            e.value = null;
            tab[i] = null;
            size--;
        } else {
            //如果key不为null,将当前位置的key进行hash查找位置。如果得出来得位置和当前位置不同,则代表
            //是从最开始得节点进行hash碰撞(向下一节点延申)得到得位置,则将当前entry的值放到从h开始第一个为null的entry位置
            int h = k.threadLocalHashCode & (len - 1);
            if (h != i) {
                tab[i] = null;

                while (tab[h] != null)
                    h = nextIndex(h, len);
                tab[h] = e;
            }
        }
    }
    return i;
}

3.ThreadLocal中的set()方法中存在key为null的情况

image.png ThreadLocalMap中entry中的key为ThreadLocal的弱引用,将ThreadLocal设置为null时,只存在key对ThreadLocal对象存在弱引用,会在gc进行回收,使得key为null。这些key为null的值不会被使用,造成内存泄漏,因此在set(),get(),remove()方法中会将部分key为null的entry释放掉。

image.png

4.子线程会继承父线程的变量:InheritableThreadLocal

在Thread中存在inheritableThreadLocals属性

public class Thread implements Runnable {

    ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
    
  
    public Thread(Runnable target) {
        init(null, target, "Thread-" + nextThreadNum(), 0);
    }

    private void init(ThreadGroup g, Runnable target, String name, long stackSize) {
        init(g, target, name, stackSize, null, true);
    }


    private void init(ThreadGroup g, Runnable target, String name, long stackSize, AccessControlContext acc, boolean inheritThreadLocals) {
        ......省略部分代码
        
        Thread parent = currentThread();
        //当前线程的inheritableThreadLocals不为null,当前线程中的值拷贝一份给子线程
        if (inheritThreadLocals && parent.inheritableThreadLocals != null)
            this.inheritableThreadLocals = ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
    }
}

子线程可以获得和父线程中的值

public class TestInheritableThreadLocal {
    private ThreadLocal<String> threadLocal = new ThreadLocal<>();
    private InheritableThreadLocal<String> inheritableThreadLocal = new InheritableThreadLocal<>();

    @Test
    void test(){
        threadLocal.set("hello threadLocal");
        inheritableThreadLocal.set("hello inheritableThreadLocal");
        new Thread(()->{
            System.out.println(threadLocal.get());
            System.out.println(inheritableThreadLocal.get());
        }).start();
    }
}

image.png