一:使用
public class UseThreadLocal {
private static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>() {
@Override
protected Integer initialValue() {
return 0;
}
};
private static ThreadLocal<Integer> threadLocal2 = new ThreadLocal<Integer>() {
@Override
protected Integer initialValue() {
return 100;
}
};
/**
* 运行3个线程
*/
public void startThreadArray() {
Thread[] runs = new Thread[3];
for (int i = 0; i < runs.length; i++) {
runs[i] = new Thread(new TestRunnable(i));
}
for (int i = 0; i < runs.length; i++) {
runs[i].start();
}
}
/**
* 测试线程,线程的工作是将ThreadLocal变量的值变化,并写回,看看线程之间是否会互相影响
*/
public static class TestRunnable implements Runnable {
int id;
public TestRunnable(int id) {
this.id = id;
}
public void run() {
Integer initialValue = threadLocal.get();
initialValue = initialValue + id;
threadLocal.set(initialValue);
System.out.println(Thread.currentThread().getName()
+ ":" + threadLocal.get());
threadLocal.remove();
Integer initialValue2 = threadLocal2.get();
initialValue2 = initialValue2 + id;
threadLocal2.set(initialValue2);
System.out.println(Thread.currentThread().getName()
+ ":" + threadLocal2.get());
threadLocal2.remove();
}
}
public static void main(String[] args) {
UseThreadLocal test = new UseThreadLocal();
test.startThreadArray();
}
}
二:源码分析
get方法
TheadLcoal对象有值的话获取并设置,没有的话创建
public T get() {
//当前线程作为key,获取线程独有的Trheadlocalmap
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
//当前threadload作为键,获取真正存储的值
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
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;
}
ThreadLocalMap
从上get源码分析得知TheadLocal对象用把当前线程作为key,获取每个线程独有的ThreadLocalMap。
ThreadLocalMap使用当前ThreadLocal对象作为key,获取每个线程的值。
通过这样的机制,多个线程使用同一个TheadLocal对象,TheadLocal对象在每个线程里面获取的值都是该线程独有的值,从而达到线程隔离的目的。
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;
}
}
...
private Entry[] table;
ThreadLocalMap 存放着Entry数组,意味着一个线程可以存放多个变量。
整体结构
三:ThreadLocal可能引发的内存泄露
key因为是弱引用,gc发生的时候可以被回收,但是由于map里面的value是强引用,所以不进行clear的话,可能会发生泄露。
public void remove() {
ThreadLocalMap m = getMap(Thread.currentThread());
if (m != null)
m.remove(this);
}