- 作用
初始化ThreadLocal值
- 源码
/**
* 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();
}
/**
* 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);
else
createMap(t, value);
return value;
}
取不到值的时候会执行setInitialValue(),因此ThreadLocal设置了初始值,哪怕执行了ThreadLocal的remove方法后,执行get(),获取的也是初始值,而不是null。
- 验证
验证代码
@Test
public void testThreadLocal () throws InterruptedException {
ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 123);
System.out.println(threadLocal.get());
threadLocal.set(234);
threadLocal.remove();
System.out.println(threadLocal.get());
}
执行结果: