本文主要是介绍【多线程与高并发之ThreadLocal】——ThreadLocal源码分析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
这里写目录标题
- 前言
- 总体UML图
- ThreadLocal
- 取值
- 赋值
- 移除
- 图解ThreadLocal
- ThreadLocalMap
- 获取Key为ThreadLocal的Entry值
- 给Key为ThreadLocal的Entry赋值
- 移除Entry
- SuppliedThreadLocal
- 总结
前言
前面讲了ThreadLocal的基本知识,下面我们对ThreadLocal的源码进行分析。
总体UML图
我们首先看下ThreadLocal这个类的类图。
如图所示:ThreadLocal有两个内部类,ThreadLocalMap和SuppliedThreadLocal。
- ThreadLocalMap,这个类本质上是一个map,和HashMap之类的实现相似,依然是key-value的形式,其中有一个内部类Entry,其中key可以看做是ThreadLocal实例,实际上是持有ThreadLocal实例的弱引用(下面讲ThreadLocalMap的时候我们会讲到为什么会是弱引用)。
- SuppliedThreadLocal是JDK8新增的内部类,扩展了ThreadLocal的初始化值的方法,允许使用JDK8新增的Lambda表达式赋值。需要注意的是,函数式接口Supplier不允许为null。
ThreadLocal
根据ThreadLocal类的源码我们可以看出ThreadLocal类的主要方法有:获取get(),赋值set(T),移除remove()。下面我们依次讲解下这三个核心方法。
取值
先看下源码:
/*** 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()方法的流程如下:
- 获取当前线程t;
- 获取到当前线程t 的成员变量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;}
- 如果ThreadLocalMap不为null,从ThreadLocalMap中获取当前线程为key的Entry,如果Entry不为null时,则返回该Entry的value值。
- 如果ThreadLocalMap为null或者Entry为null,返回setInitialValue()的值。setInitialValue()调用重写的initialValue()返回新值(如果没有重写initialValue将返回默认值null),并将新值存入当前线程的ThreadLocalMap(如果当前线程没有ThreadLocalMap,会先创建一个)。
/*** Variant of set() to establish initialValue. Used instead* of set() in case user has overridden the set() method.** @return the initial value*/private T setInitialValue() {T value = initialValue();Thread t = Thread.currentThread();ThreadLocalMap map = getMap(t);if (map != null)map.set(this, value);elsecreateMap(t, value);return value;}/*** 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) {t.threadLocals = new ThreadLocalMap(this, firstValue);}
赋值
源码:
/*** 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 map = getMap(t);if (map != null)map.set(this, value);elsecreateMap(t, value);}
void set(T) 和setInitialValue类似,将新值存入当前线程的ThreadLocalMap(如果当前线程没有ThreadLocalMap,会先创建一个)。
移除
源码:
/*** 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);}
remove()方法是获取当前线程的ThreadLocalMap,若map不为空,则调用ThreadLocalMap的remove()方法移除当前ThreadLocal作为key的键值对。
图解ThreadLocal
让我们用一张图来了解下ThreadLocal,每个线程可能会有多个ThreadLocal,而每个线程中的ThreadLocal都会存放于同一个ThreadLocalMap中。但为避免占用空间较大或生命周期较长的数据常驻于内存引发一系列问题,hash table的key是弱引用WeakReferences。当空间不足时,会清理未被引用的entry。
ThreadLocalMap
ThreadLocalMap作为存储当前线程本地变量的定制化Map,仅有ThreadLocal类对其有操作权限,此定制化Map是Thread的私有属性。为避免占用空间较大或生命周期较长的数据常驻于内存引发一系列问题,hash table的key是弱引用WeakReferences。当空间不足时,会清理未被引用的entry。
内部类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;}}
其中ThreadLocalMap的Key为ThreadLocal,value为object。
接下来,我们来分析下ThreadLocalMap中的getEntry(ThreadLocal<?> key) ,set(ThreadLocal<?> key, Object value) 和remove(ThreadLocal<?> key) 三个方法。
获取Key为ThreadLocal的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) {int i = key.threadLocalHashCode & (table.length - 1);Entry e = table[i];if (e != null && e.get() == key)return e;elsereturn getEntryAfterMiss(key, i, e);}
getEntry流程如下:
- 计算Entry数组的下标索引值index:key.threadLocalHashCode & (table.length - 1);
- 获取索引对应的Entry;
- 如果返回节点entry 有值且其key未冲突(只有1个entry返回的key等于传入的key),则直接返回该entry;
- 返回entry为空或键冲突,则调用getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e)方法返回entry。
下面我们来看下getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) 这个方法做了哪些操作
getEntryAfterMiss处理那些getEntry时命中且有冲突的key。入参是当前ThreadLocal,key在数组的索引index,以及index对应的键值对。
getEntryAfterMiss源码:
/*** Version of getEntry method for use when key is not found in* its direct hash slot.** @param key the thread local object* @param i the table index for key's hash code* @param e the entry at table[i]* @return the entry associated with key, or null if no such*/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);elsei = nextIndex(i, len);e = tab[i];}return null;}
getEntryAfterMiss的流程如下:
当Entry不为空时,
- 获取entry的key;
- 如果key一致(内存地址=判断),则返回该entry;
- 如果key为null,则调用expungeStaleEntry方法擦除该entry;
- 其他情况则通过nextIndex方法获取下一个索引位置index;
- 获取新index处的entry,再次循环,直到定位到该key返回entry或者返回null。
expungeStaleEntry方法:只要key为null均会被擦除,使得对应value没有被引用,方便回收。
源码如下:
/*** 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 staleSlottab[staleSlot].value = null;tab[staleSlot] = null;size--;// Rehash until we encounter nullEntry 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;}
给Key为ThreadLocal的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;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();}
set流程如下:
- 计算Entry数组的下标索引值index:key.threadLocalHashCode & (len- 1);
- 当前index处已有entry ,并且Key相同,则更新value值;
- 出现过期数据 ,遍历清洗过期数据并在index处插入新数据,其他数据后移;
- 没有过期数据被清理且实际size超过扩容阈值,则首先调用expungeStaleEntries删除所有过期数据,如果清理数据后size>=threshold的3/4,进行2倍扩容。
size:table的实际entry数量;
扩容阈值threshold:table.length(默认16)大小的2/3;
移除Entry
移除ThreadLocal为key的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;}}}
1.计算Entry数组的下标索引值index:key.threadLocalHashCode & (len- 1);
2.当前index处已有entry ,并且Key相同,则进行移除操作。
SuppliedThreadLocal
SuppliedThreadLocal是JDK8新增的内部类,扩展了ThreadLocal的初始化值的方法,允许使用JDK8新增的Lambda表达式赋值。需要注意的是,函数式接口Supplier不允许为null。
源码如下:
/*** An extension of ThreadLocal that obtains its initial value from* the specified {@code 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);}@Overrideprotected T initialValue() {return supplier.get();}}
总结
看了类图,总结了源码之后,对于ThreadLocal有了一个更清晰的认识。ThreadLocalMap作为一个定制化的Map来存储当前线程的本地变量值,它和HashMap同样都是Key-Value型的键值对,但两者又有其不同。那两者具体有哪些相似和不同呢,期待我的下篇博客吧。
这篇关于【多线程与高并发之ThreadLocal】——ThreadLocal源码分析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!