本质上,ThreadLocal通过空间来换取时间,从而实现每个线程当中都会有一个变量的副本,这样每个线程就会操作改副本,从而完全规避了多线程的并发问题。
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();
}
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
静态内部类
static class ThreadLocalMap {
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
...
}
每个线程Thread都维护了自己的threadLocals变量,所以在每个线程创建ThreadLocal的时候,实际上数据是存在自己线程Thread的threadLocals变量里面的,别人没办法拿到,从而实现了隔离。
public
class Thread implements Runnable {
...
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;
...
}
Java中存在四种类型的引用:
除了强引用用=new,其他三种都继承Reference:
public class WeakReference<T> extends Reference<T> {
}
防止内存泄漏,如果Entry是强引用,Entry中的k永远无法得到释放,k,v越来越多。。。如果Entry是弱引用,在下一次垃圾回收的时候,弱引用ThreadLocal将会被回收。
static class Entry extends WeakReference<ThreadLocal<?>> {
}
Entry:k,v
Entry是弱引用,在下一次垃圾回收的时候,弱引用ThreadLocal将会被回收。Entry的k将指向null(k指向的ThreadLocal已经被回收),v将不能再被获取。造成内存泄漏。
ThreadLocal在set或者get方法的时候,程序会检查Entry数组,将k为null的Entry一一remove掉。
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;
}
// 替换k为空的Entry
if (k == null) {
replaceStaleEntry(key, value, i);
return;
}
}
tab[i] = new Entry(key, value);
int sz = ++size;
if (!cleanSomeSlots(i, sz) && sz >= threshold)
rehash();
}
在使用完ThreadLocal后执行remove方法
package com.learn.thread.local
public class ThreadLocalTest {
private static final ThreadLocal<String> name = new ThreadLocal();
public static void main(String[] args) {
try {
name.set("John");
System.out.println(checkUser());
} finally {
name.remove();
}
System.out.println(name.get());
}
public static String checkUser() {
if (name.get() == null) {
return "";
}
return name.get();
}
}