随笔分类
threadLocal
入门
保存thread的临时信息
和thread绑定在一起
这个区域不一定要用,但也是不可或缺的存在
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */ //属于这个线程的threadLocal,Map由ThreadLocal来维护
ThreadLocal.ThreadLocalMap threadLocals = null;
/*
* InheritableThreadLocal values pertaining to this thread. This map is
* maintained by the InheritableThreadLocal class.//属于这个线程的InheritablethreadLocal,Map由InheritableThreadLocal来维护
*/
ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
Thread默认构造时inheritThreadLocals默认值为true
父线程可以通过内在继承inheritThreadLocals来给子线程传递一些信息
if (inheritThreadLocals && parent.inheritableThreadLocals != null) //当父线程的inhertitableThreadLocals不为null时,子类便可以去继承它
this.inheritableThreadLocals =
ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
/* Stash the specified stack size in case the VM cares */
但有一个构造函数除外
/**
* Creates a new Thread that inherits the given AccessControlContext
* but thread-local variables are not inherited.
* This is not a public constructor.
*/
Thread(Runnable target, AccessControlContext acc) {
this(null, target, "Thread-" + nextThreadNum(), 0, acc, false);
}
概念
JDK介绍
/**
* This class provides thread-local variables. These variables differ from
* their normal counterparts in that each thread that accesses one (via its
* {@code get} or {@code set} method) has its own, independently initialized
* copy of the variable. {@code ThreadLocal} instances are typically private
* static fields in classes that wish to associate state with a thread (e.g.,
* a user ID or Transaction ID).
*
* <p>For example, the class below generates unique identifiers local to each
* thread.
* A thread's id is assigned the first time it invokes {@code ThreadId.get()}
* and remains unchanged on subsequent calls.
* <pre>
* import java.util.concurrent.atomic.AtomicInteger;
*
* public class ThreadId {
* // Atomic integer containing the next thread ID to be assigned
* private static final AtomicInteger nextId = new AtomicInteger(0);
*
* // Thread local variable containing each thread's ID
* private static final ThreadLocal<Integer> threadId =
* new ThreadLocal<Integer>() {
* @Override protected Integer initialValue() {
* return nextId.getAndIncrement();
* }
* };
*
* // Returns the current thread's unique ID, assigning it if necessary
* public static int get() {
* return threadId.get();
* }
* }
* </pre>
* <p>Each thread holds an implicit reference to its copy of a thread-local
* variable as long as the thread is alive and the {@code ThreadLocal}
* instance is accessible; after a thread goes away, all of its copies of
* thread-local instances are subject to garbage collection (unless other
* references to these copies exist).
*
* @author Josh Bloch and Doug Lea
* @since 1.2
*/
public class ThreadLocal<T> {
ThreadLocal类是用来提供线程内部的局部变量.这种变量在多线程环境下访问(通过get和set方法)时能够保证各个线程的变量相对独立于其他线程内的变量
private static final ThreadLocal<Integer> threadId =
* new ThreadLocal<Integer>
可以看出,ThreadLocal实例通常来说是private static类型的,用于关联线程和线程上下文
ThreadLocal的作用:提供线程内的局部变量,不同的线程之间不会相互干扰,这种变量在线程的生命周期内起作用,有效地减少了同一个线程内多个函数或组件之间传递公共变量的复杂度(和域对象有点相似)
总结:
1.线程并发:在高并发下,须要保证线程的隔离性
2.保存并传递数据(有生命周期,比如说人有生命大限,但有记忆功能)
3.线程隔离:每个线程中的变量是独立的,不会相互影响
方法声明 | 描述 |
---|---|
protected T initialValue() | 返回当前线程局部变量的初始值 |
public void set(T value) | 设置当前线程绑定的局部变量 |
public T get() | 获取当前线程绑定的局部变量 |
public void remove() | 移除当前线程绑定的局部变量 |
初探
为什么要有ThreadLocal呢
因为在高并发下,线程是抢占式获取CPU的
这是无法保证线程内数据的隔离性(其实加锁就行,但显然这不是一个明智的做法,会影响并发效率,最佳的方法还是无锁
看个案例
/**
* 由运行结果可以看出,并没有保证线程数据的隔离性
* Thread-0--->Thread-2的数据
* ------------------
* Thread-4--->Thread-2的数据
* ------------------
* Thread-3--->Thread-3的数据
* ------------------
* Thread-2--->Thread-2的数据
* ------------------
* Thread-1--->Thread-1的数据
* ------------------
*
* Process finished with exit code 0
*/
public class ThreadLocalDemo {
private String content;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public static void main(String[] args) {
ThreadLocalDemo localDemo = new ThreadLocalDemo();
for (int i = 0; i < 5; i++){
new Thread(() -> {
localDemo.setContent(Thread.currentThread().getName() + "的数据");
System.out.println(Thread.currentThread().getName() + "--->" + localDemo.getContent());
System.out.println("------------------");
}).start();
}
}
}
这个时候便可以使用ThreadLocal
/**
* Thread-0--->Thread-0的数据
* ------------------
* Thread-2--->Thread-2的数据
* ------------------
* Thread-4--->Thread-4的数据
* ------------------
* Thread-1--->Thread-1的数据
* ------------------
* Thread-3--->Thread-3的数据
* ------------------
*
* Process finished with exit code 0
*/
public class ThreadLocalDemo {
private String content;
ThreadLocal<String> threadLocal = new ThreadLocal<>();
public String getContent() {
return threadLocal.get();
}
public void setContent(String content) {
threadLocal.set(content);
}
public static void main(String[] args) {
ThreadLocalDemo localDemo = new ThreadLocalDemo();
for (int i = 0; i < 5; i++){
new Thread(() -> {
localDemo.setContent(Thread.currentThread().getName() + "的数据");
System.out.println(Thread.currentThread().getName() + "--->" + localDemo.getContent());
System.out.println("------------------");
}).start();
}
}
}
对比ThreadLocal和synchronized
synchronized | ThreadLocal | |
---|---|---|
原理 | 同步方式采用"以时间换空间"的策略,线程排队去访问同一份变量 | 采用"空间换时间"策略,为每一个线程都提供了一份变量的副本,实现同时访问且互不干扰 |
侧重点 | 多个线程之间访问资源的同步 | 多线程中每个线程中数据的隔离性 |
显然ThreadLocal能够保证更高的并发性
再探
现在的ThreadLocal的设计方案已经完全不一样看了
具体
- 每一个线程内都有一个ThreadLocalMap
- Map里面存储的是ThreadLocal对象(key)和线程的变量副本(value)
- Thread的内部Map是由ThreadLocal来维护的,由ThreadLocal负责向Map获取和设置线程的变量值
- 对于不同的线程,每次获取副本值时,别的线程并不能获取当前线程的副本值,实现了副本的隔离
这样设计的好处:
- 每个Map里面设置的Entry数量变少
- 当Thread销毁时,ThreadLocalMap也会随之销毁,这也减少了内存的占用
源码分析
Set
/**
* 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,也就是threadLocals
ThreadLocalMap map = getMap(t);
if (map != null) { //判断Map是否为空
map.set(this, value); //将ThreadLocal作为键,value作为值,设置到Map中去
} else {
createMap(t, value);//如果Map不存在,对Map进行初始化,第一个参数为当前线程,第二个为当前线程预绑定的值,这里的传参应该是要设置初始值
}
}
/**
* 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
}
/**
* 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) {//真相了,如果Map不存在,即来设置初始值
t.threadLocals = new ThreadLocalMap(this, firstValue);//当前线程的ThreadLocalMap的第一个Entry是<ThreadLocal,firstValue>
}
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 map = getMap(t);//获取当前线程维护着的ThreadLocalMap
if (map != null) {//如果Map不存在,直接return
ThreadLocalMap.Entry e = map.getEntry(this);//以ThreadLocal为键去Map中找对应Entry
if (e != null) {//如果与当前线程绑定的Entry不存在,也进行return
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;//返回获取的值
}
}
return setInitialValue();//返回初始值
}
/**
* 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;
else
return getEntryAfterMiss(key, i, e);
}
/**
* 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();//这里的value其实就是null
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
map.set(this, value);//设置value的初始值,键还是LocalValue
} else {
createMap(t, value);//如果Map不存在,则将ThreadLocal的引用和value(null)作为Map的FirstKey和FirstValue
}
if (this instanceof TerminatingThreadLocal) {
TerminatingThreadLocal.register((TerminatingThreadLocal<?>) this);
}
return value;
}
/**
* Returns the current thread's "initial value" for this
* thread-local variable. //返回当前线程对应的ThreadLocal初始值
*This method will be invoked the first
* time a thread accesses the variable with the {@link #get}
* method, //此方法的第一次调用发生在线程通过get访问此线程的ThreadLocal值时,
* unless the thread previously invoked the {@link #set}
* method, //除非线程先去调用了ser方法
* in which case the {@code initialValue} method will not
* be invoked for the thread. //在这种情况下,initialValue才不会被线程调用
* Normally, this method is invoked at
* most once per thread, //通常情况下,每个线程最多调用一次这个方法
* but it may be invoked again in case of
* subsequent invocations of {@link #remove} followed by {@link #get}.
*
* <p>This implementation simply returns {@code null}; if the
* programmer desires thread-local variables to have an initial
* value other than {@code null}, {@code ThreadLocal} must be
* subclassed, and this method overridden. Typically, an
* anonymous inner class will be used.
*
* @return the initial value for this thread-local
*/
protected T initialValue() {//protected修饰,如果不想默认返回null的话,可以去使用子类覆盖实现
return null;
}
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());//获取当前线程的ThreadLocalMap
if (m != null) {
m.remove(this);//移除当前ThreadLocal对象对应的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;
}
}
}
ThreadLocalMap
在分析ThreadLocal方法时,了解到ThreadLocal的操作实际上是围绕ThreadLocalMap展开的
那么ThreadLocalMap的基本结构又是怎样的呢?
ThreadLocalMap是ThreadLocal的一个静态内部类,它没有去实现Map接口,用独立的方法区实现了Map的功能
其内部的Entry也是独立实现的
Entry继承了弱引用WeakReference
- 弱引用:GC时只要发现了只具有弱引用的对象,不挂当前内存空间足够与否,都会回收它的内存
/**
* ThreadLocalMap is a customized hash map suitable only for
* maintaining thread local values. No operations are exported
* outside of the ThreadLocal class. The class is package private to
* allow declaration of fields in class Thread. To help deal with
* very large and long-lived usages, the hash table entries use
* WeakReferences for keys. However, since reference queues are not
* used, stale entries are guaranteed to be removed only when
* the table starts running out of space.
*/
static class ThreadLocalMap {//静态内部类
/**
* 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<?>> {//Entry继承了弱引用
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {//可见,Entry的键只能是ThreadLocal,这是绑定死的
super(k);
value = v;
}
}
/**
* The initial capacity -- MUST be a power of two.
* 初始容量,必须是2的整数倍
*/
private static final int INITIAL_CAPACITY = 16;
/**
* The table, resized as necessary.
* table.length MUST always be a power of two.
* 存放数据的table,大小同样也必须是2的整数倍
*/
private Entry[] table;
/**
* The number of entries in the table.
* table里entry的个数,即用于判断当前table的使用量是否超过阈值
*/
private int size = 0;
/**
* The next size value at which to resize.
* 进行扩容的阈值,table使用量大于它是进行扩容
*/
private int threshold; // Default to 0
Entry实现了弱引用还会发生内存泄漏吗?
假设Entry中的Key使用了强引用
-
假设在业务代码中使用完ThreadLocal后,栈中的ThreadLocal Ref就出栈了
-
但由于Entry实现了强引用,即Key强引用了ThreadLocal导致其不能被GC
-
在CurrentThread依然运行或者Map中这个Entry没有被删除的情况下,
始终存在着这么一条强引用链 CurrentThread Ref --> CurrentThread --> ThreadLocalMap -->Entry(<ThreadLoca,Value>) ,即Entry无法被回收,Entry将内存泄漏
也就是说Entry实现了强引用,即Key使用了强引用,并没有避免内存泄漏问题
强引用不行,弱引用怎么样?
同样来进行分析
- 当业务层使用完ThreadLocal之后,栈中对应引用被回收了
- 由于此时Key是弱引用指向了ThreadLocal,而ThreadLocal没有被其他引用(强)所执行,所以发生GC时,ThreadLocal就被回收掉了,此时Map中存有的Entry对应Key已经是null了,这也就意味着该value不会再被访问
- 但是在没有手动删除Entry或CurrentThread依然运行的情况下,依然存在这样的强引用链 CurrentThread Ref --> CurrentThread --> ThreadLocalMap -->Entry(<ThreadLoca,Value>) ,这也就意味着Entry依然不会被回收,可value已经不会再被访问到,即value发生了内存泄漏
由此可知无论key是使用强引用还是弱引用,都无法避免内存泄漏的发生
细究内存泄漏
有上述可知,无论key是使用了强引用还是弱引用,都不能避免内存泄漏的发生
那内存泄露发生的真实原因是什么?
上面已经提过,无论是强引用还是弱引用,内存泄漏发生都有着相同的前提
-
没有手动去删除Entry
可以在使用完LocalThread之后手动来删除Entry即可避免内存泄漏的发生
-
当前线程依然运行
ThreadLocalMap是Thread的一个成员变量,即它被当前Thread所强引用着,所以ThreadLocalMap的生命周期和当前线程一样长,如果说ThreadLocal不被使用后,CurrentThread也随之执行结束,那么就不会发生内存泄漏,因为ThreadLocalMap GC时也会被回收
可以理解,ThreadLocal发生内存泄漏的根源在于:由于ThreadLocalMap的生命周期和Thread一样长,如果在ThreadLocal不再使用后没有去手动删除对应Entry的话,就会发生内存泄漏
为什么Entry选择去实现了弱引用?
因为使用弱引用比使用强引用多了一层保障
使用弱引用,首先可以来保证ThreadLocal在不使用之后发生GC时可以被回收掉
其次,弱引用发生的是Value的内存泄漏
但是观看源码之后,发现不简单!
首先得知道,当前entry的key是null了
首先来看ThreadLocalMap的getEntry方法
/**
* 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];//获取哈希索引对应位置的entry
if (e != null && e.get() == key)
return e;
else
return getEntryAfterMiss(key, i, e);//e.get()此时是null,执行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)//k是null,之后执行expungeStaleEntry(i),把对应哈希索引作为参数传递过去
expungeStaleEntry(i);
else
i = nextIndex(i, len);
e = tab[i];
}
return null;
}
/**
* 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
tab[staleSlot].value = null;//真相了,原来对应ThreadLocal位置处的value设置为null,这也就避免了内存泄漏的发生
tab[staleSlot] = null;//对应位置的哈希数组元素设置为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;
}
在来看看set方法
/**
* 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) {//可知,k为null,执行replaceStaleEntry方法
replaceStaleEntry(key, value, i);
return;
}
}
tab[i] = new Entry(key, value);
int sz = ++size;
if (!cleanSomeSlots(i, sz) && sz >= threshold)
rehash();
}
/**
* Replace a stale entry encountered during a set operation
* with an entry for the specified key. The value passed in
* the value parameter is stored in the entry, whether or not
* an entry already exists for the specified key.
*
* As a side effect, this method expunges all stale entries in the
* "run" containing the stale entry. (A run is a sequence of entries
* between two null slots.)
*
* @param key the key
* @param value the value to be associated with key
* @param staleSlot index of the first stale entry encountered while
* searching for key.
*/
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;
for (int i = prevIndex(staleSlot, len);
(e = tab[i]) != null;
i = prevIndex(i, len))
if (e.get() == null)
slotToExpunge = i;
// Find either the key or trailing null slot of run, whichever
// occurs first
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为null,此方法会跳过
e.value = value;
tab[i] = tab[staleSlot];
tab[staleSlot] = e;
// Start expunge at preceding stale entry if it exists
if (slotToExpunge == staleSlot)
slotToExpunge = i;
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.
if (k == null && slotToExpunge == staleSlot)
slotToExpunge = i;
}
// If key not found, put new entry in stale slot
//如果key是null的话,就放置新的entry到原来位置处
tab[staleSlot].value = null;//将原先ThreadLocal对应的Value设置为null,value得以回收
tab[staleSlot] = new Entry(key, value);//放置新的Entry
// If there are any other stale entries in run, expunge them
if (slotToExpunge != staleSlot)
cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
}
以上不就是弱引用所提供的保障吗?
即在ThreadLocal被回收之后,Entry没有被remove时,只要有调用getEntry或者set方法,都会将Value设置为null,value得以回收,这不就能避免Value的内存泄漏吗?
hash冲突
先来看看我们createMap是调用的ThreadLocalMap构造函数
/**
* Construct a new map initially containing (firstKey, firstValue).
* ThreadLocalMaps are constructed lazily, so we only create
* one when we have at least one entry to put in it.
*/
ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
//初始化table, --> Entry[] table,初始长度16
table = new Entry[INITIAL_CAPACITY];
//计算索引
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
//设置值
table[i] = new Entry(firstKey, firstValue);
//当前table里Entry数为1
size = 1;
//设置阈值,并非直接等于16!
setThreshold(INITIAL_CAPACITY);
}
重点来看看索引的计算 firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
-
firstKey.threadLocalHashCode
这是一个十分神奇的哈希算法
public class ThreadLocal
{ /** * ThreadLocals rely on per-thread linear-probe hash maps attached * to each thread (Thread.threadLocals and * inheritableThreadLocals). The ThreadLocal objects act as keys, * searched via threadLocalHashCode. This is a custom hash code * (useful only within ThreadLocalMaps) that eliminates collisions * in the common case where consecutively constructed ThreadLocals * are used by the same threads, while remaining well-behaved in * less common cases. */ private final int threadLocalHashCode = nextHashCode();//final类型,避免恶意修改,此处调用了nextHashCode() /** * Returns the next hash code. */ private static int nextHashCode() { return nextHashCode.getAndAdd(HASH_INCREMENT);//而nextHashCode是什么?接着看 } /** * The next hash code to be given out. Updated atomically. Starts at * zero. * 每有一个新的ThreadLocal调用nextHashCode,此nextHashCode会自动增加 */ //AtomicInteger是一个提供原子操作的Integer类,通过线程安全的方式来进行加减操作,适合高并发下使用 private static AtomicInteger nextHashCode = new AtomicInteger(); /** * The difference between successively generated hash codes - turns * implicit sequential thread-local IDs into near-optimally spread * multiplicative hash values for power-of-two-sized tables. */ //这个HASH_INCREMENT是一个比较特殊的哈希值,其目的为了能让哈希码能够比较均匀的分布在2的n次方数组里,即Entry[] table,这样能够尽量避免Hash冲突 private static final int HASH_INCREMENT = 0x61c88647;
这也就能保证不同ThreadLocal的ThreadLocalHashCode不一样了(其实这么讲不怎么准确),也就是说每当有一个新的ThreadLocal调用ThreadLocalHashCode时,原本上一个ThreadLocal的所属类的类变量nextHashCode就会更新,返回一个新的nextHashCode赋值给当前ThreadLocal的ThreadLocalHashCode,因为ThreadLocalHashCode每一个ThreadLocal独享一份,且在初次复制之后便不可变,这也恰恰满足了我们的需求
-
(INITIAL_CAPACITY - 1)
计算Hash时采用了HashCode & (INITIAL_CAPACITY - 1)的算法,
首先这样能够保证计算出来的索引不会越界
其次这是个比较高效的实现 HashCode % INITIAL_CAPACITY 运算
能够有效减少
再来看看ThreadLocalMap的set方法
线性探索法
/**
* 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) { //key相同即为覆盖原先的值
e.value = value;
return;
}
if (k == null) { //key为null,也就是之前将的弱引用的保障,将对于value设为null,然后设置新的Entry覆盖原先处
replaceStaleEntry(key, value, i);
return;
}
}
//线性探索完数组,既没有找到对于Key的Entry,也没有找的空的Entry
tab[i] = new Entry(key, value);//此时的tab[i]是空的,不然在没有return的情况下是出不来的,于此处设置新的Entry
int sz = ++size;
if (!cleanSomeSlots(i, sz) && sz >= threshold) //如果调用了cleanSomeSlots之后没有Entry被回收并且当前tab的使用量达到了负载因子所定义的长度,ThreadLocalMap的构造函数便将threshold便将其设置为数组大小的 2 / 3
rehash();//重新哈希,rehash做了什么,接着往下看
}
/**
* Increment i modulo len.
* 获取环形数组的下一个索引位置
* 可以看出,底层实现遍历就是把Entry[] tabel当成了一个环形数组
*/
private static int nextIndex(int i, int len) {
return ((i + 1 < len) ? i + 1 : 0);
}
思考个问题
会不会出现在for循环里既找不到对应key的Entry,也没有找到空的Entry,由此造成的死循环问题?
其实是不会的
这取决于HashTable的负载因子,和Redis有点相似
/**
* Heuristically scan some cells looking for stale entries.
* This is invoked when either a new element is added, or
* another stale one has been expunged. It performs a
* logarithmic number of scans, as a balance between no
* scanning (fast but retains garbage) and a number of scans
* proportional to number of elements, that would find all
* garbage but would cause some insertions to take O(n) time.
*
* @param i a position known NOT to hold a stale entry. The
* scan starts at the element after i.
*
* @param n scan control: {@code log2(n)} cells are scanned,
* unless a stale entry is found, in which case
* {@code log2(table.length)-1} additional cells are scanned.
* When called from insertions, this parameter is the number
* of elements, but when from replaceStaleEntry, it is the
* table length. (Note: all this could be changed to be either
* more or less aggressive by weighting n instead of just
* using straight log n. But this version is simple, fast, and
* seems to work well.)
*
* @return true if any stale entries have been removed.
*/
private boolean cleanSomeSlots(int i, int n) {
boolean removed = false;
Entry[] tab = table;
int len = tab.length;
do {
i = nextIndex(i, len);
Entry e = tab[i];
if (e != null && e.get() == null) { //寻找threadLocal已经被回收但是Entry还存在的元素
n = len;
removed = true;
i = expungeStaleEntry(i);//expungeStaleEntry就是清除对应位置的Value,并将对应位置处的数组设置为Null,达到清除的无用Entry的效果
}
} while ( (n >>>= 1) != 0);
return removed;//如果有Entry被回收的话,此时removed应为true
}
/**
* Set the resize threshold to maintain at worst a 2/3 load factor.
*/
private void setThreshold(int len) {
threshold = len * 2 / 3;
}
进行rehash
private void rehash() {
expungeStaleEntries();//进行全表的清理扫描
// Use lower threshold for doubling to avoid hysteresis
if (size >= threshold - threshold / 4)
resize();//重新设置table大小,这里就不再展开了
}
综上所述,是不会出现for死循环的情况,因为table数组就没有满,所以必然存在空的Entry
源于无用Entry的清理以及负载因子的存在,进行rahash