不能解决共享变量的并发问题,只能维护本线程变量
作用 | API |
---|---|
创建本地线程变量 | ThreadLocal() |
获取当前线程存放的变量 | get() |
设置当前线程要存放的变量 | set(T value) |
移除当前线程的变量 | remove() |
原理
各线程持有一个用于存放变量的map(ThreadLocalMap),以变量对应的ThreadLocal自身为键
应用场景
数据库连接
Session管理
//获取线程中本地变量map的值(键为当前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();
}
/**
* 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;
}
//设置线程中本地变量map的值(键为当前ThreadLocal)
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
//移除线程中本地变量map的值(键为当前ThreadLocal)
public void remove() {
ThreadLocalMap m = getMap(Thread.currentThread());
if (m != null)
m.remove(this);
}
//获取线程的本地变量map
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
//为线程初始化其本地变量map
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
网友评论