- 作用
初始化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());
}
执行结果:

本文详细介绍了ThreadLocal的作用及其实现原理,特别是初始化过程和如何获取当前线程的值。通过示例代码验证了即使调用了remove方法,再次获取时依然能返回初始值而非null的特点。
972

被折叠的 条评论
为什么被折叠?



