1.基本介绍
ThreadLocal提供了线程本地变量,它可以保证访问到的变量属于当前线程,每个线程都保存有一个变量副本,每个线程的变量都不同,而同一个线程在任何时候访问这个本地变量的结果都是一致的。
2.一个简单的例子
ThreadLocal通常定义为private static类型。下面是一个简单的例子了解基本用法,之后我们研究原理
public class ThreadLocalTest {
public static class MyRunnable implements Runnable {
private static ThreadLocal<Integer> threadLocal = new ThreadLocal();
@Override
public void run() {
threadLocal.set((int) (Math.random() * 100D));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(threadLocal.get());
}
}
public static void main(String[] args) {
MyRunnable sharedRunnableInstance = new MyRunnable();
Thread thread1 = new Thread(sharedRunnableInstance);
Thread thread2 = new Thread(sharedRunnableInstance);
thread1.start();
thread2.start();
}
}
输出(一次可能的输出)
32
61
3.源码分析
为了弄清为什么不同线程调用get方法的时候都是自己的本地变量我们就粗暴的直接看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();//1.获取当前调用的线程
ThreadLocalMap map = getMap(t);//2.获取ThreadLocalMap
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);//3获取真正的值
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
通过源码我们可以发现,1.获取当前调用的线程2处获取了一个map,这个具体的实现如下
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
可以看出这是线程的一个内部变量,ThreadLocalMap是ThreadLocal的一个静态内部类。
//Thread.class
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;
下面我们继续分析到3处,这里拿到线程自己的map之后
map.getEntry(this)
也就是theadLocal自身作为key,然后获取到对应的值,看下ThreadLocalMap的部分源码:
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<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
/**
* 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 = new Entry[INITIAL_CAPACITY];
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
table[i] = new Entry(firstKey, firstValue);
size = 1;
setThreshold(INITIAL_CAPACITY);
}
可以看出存储的key值本质上是threadLocal.threadLocalHashCode.那这个threadLocalHashCode是怎么保证唯一性呢,继续看
private final int threadLocalHashCode = nextHashCode();
//继续跟踪
private static final int HASH_INCREMENT = 0x61c88647;
/**
* Returns the next hash code.
*/
private static int nextHashCode() {
return nextHashCode.getAndAdd(HASH_INCREMENT);
}
到这一步,大体上也许就能明白基本原理,当然里面还有许多细节,希望大家能够自己看源码来加深理解。
简单总结:
- 1.重要的是理清Thread、ThreadLocal 和ThreadLocalMap三者之间的关系。
- 2.ThreadLocalMap解决冲突的方法是线性探测法(不断加1),而不是HashMap的链地址法,这一点也能从ThreadLocalMap源码中Entry的结构上看出来。
- 3.ThreadLocalMap中的Entry的key实现了弱引用,这样可以让无用的key及时的回收,Entry中Value的清理发生在调用set()或者remove() 方法是可能会触发expungeStaleEntry()方法来清理无用的Entry。
4.使用注意点
1.每次使用完ThreadLocal,都调用它的remove()方法,清除数据。
2.当和线程池使用时尤其要注意,没有及时清理ThreadLocal,不仅是内存泄漏的问题,更严重的是可能导致业务逻辑出现问题。
3.线程池和InheritableThreadLocal使用更加需要注意,InheritableThreadLocal并不是线程安全的,怎么说呢,这要从InheritableThreadLocal的实现原理讲起。
在新创建线程的时候,会调用new Thead()
public Thread() {
init(null, null, "Thread-" + nextThreadNum(), 0);
}
然后继续跟:
private void init(ThreadGroup g, Runnable target, String name,long stackSize) {
init(g, target, name, stackSize, null);
}
继续
private void init(ThreadGroup g, Runnable target, String name,
long stackSize, AccessControlContext acc) {
......
if (parent.inheritableThreadLocals != null)
this.inheritableThreadLocals =
ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
......
}
///////////////////
static ThreadLocalMap createInheritedMap(ThreadLocalMap parentMap) {
return new ThreadLocalMap(parentMap);
}
//////////////////
/**
* Construct a new map including all Inheritable ThreadLocals
* from given parent map. Called only by createInheritedMap.
*
* @param parentMap the map associated with parent thread.
*/
private ThreadLocalMap(ThreadLocalMap parentMap) {
Entry[] parentTable = parentMap.table;
int len = parentTable.length;
setThreshold(len);
table = new Entry[len];
for (int j = 0; j < len; j++) {
Entry e = parentTable[j];
if (e != null) {
ThreadLocal key = e.get();
if (key != null) {
Object value = key.childValue(e.value);
Entry c = new Entry(key, value);
int h = key.threadLocalHashCode & (len - 1);
while (table[h] != null)
h = nextIndex(h, len);
table[h] = c;
size++;
}
}
}
}
最终,会把父线程的ThreadLocalMap 复制一份到子线程中,划重点------关键的一句是:
Object value = key.childValue(e.value);
那么 childValue方法是实现是什么呢?查看源码发现InheritableThreadLocal 中的实现
/**
* Computes the child's initial value for this inheritable thread-local
* variable as a function of the parent's value at the time the child
* thread is created. This method is called from within the parent
* thread before the child is started.
* <p>
* This method merely returns its input argument, and should be overridden
* if a different behavior is desired.
*
* @param parentValue the parent thread's value
* @return the child thread's initial value
*/
protected T childValue(T parentValue) {
return parentValue;
}
默认直接return 父线程的parentValue,所以这样就导致子线程和父线程指向的是同一个对象,这里并不是值传递,而是引用传递。而且,仔细看注释
* This method merely returns its input argument, and should be overridden
* if a different behavior is desired.
注释说明如果有特定的需求,这个方法应该被覆写!!!
由于返回的是引用,这样我们线程池中很多的线程都会共用一个ThreadLocal,当其中一个更新了ThreadLocal的值后,就会影响其他的线程,所以就出现了我们最开始提到的场景,那么如果我非要使用InheritableThreadLocal呢?方法就是覆写 childValue方法,保证是值传递而不是引用传递。
网友评论