最近在熟悉公司业务代码的时候发现有使用了ThreadLocal去控制线程变量的部分,特此学习一下
ThreadLocal
ThreadLocal提供了线程内存储变量的能力,这些变量不同之处在于每一个线程读取的变量是对应的互相独立的。通过get和set方法就可以得到当前线程对应的值。
创建ThreadLocal:这里实例化的是InheritableThreadLocal,
因为这样父线程生成的变量就可以传递到子线程中进行使用(看业务需求使用)
private static final ThreadLocal<CommonInvocationInfo> threadLocal = new InheritableThreadLocal<>();
ThreadLocal的set方法
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
createMap():
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
map.set()调用的是ThreadLocalMap中的set():
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;
}
if (k == null) {
replaceStaleEntry(key, value, i);
return;
}
}
tab[i] = new Entry(key, value);
int sz = ++size;
if (!cleanSomeSlots(i, sz) && sz >= threshold)
rehash();
}
看一下其构造方法,其实ThreadLocalMap就是一个Entry数组,封装着线程所需存储的变量
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);
}
这里的Entry是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;
}
}
/**
* The initial capacity -- MUST be a power of two.
*/
private static final int INITIAL_CAPACITY = 16;
/**
* The table, resized as necessary.
* table.length MUST always be a power of two.
*/
private Entry[] table;
...
get方法:可以发现ThreadLocal是根据 ThreadLocalMap(这里其实是一个静态内部类) 维护的
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();
}
getMap():从当前Thread获取threadlocal
/**
* Get the map associated with a ThreadLocal. Overridden in
* InheritableThreadLocal.
*
* @param t the current thread
* @return the map
*/
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
同样这里getEntry()调用的是ThreadLocalMap中的
private Entry getEntry(ThreadLocal<?> key) {
int i = key.threadLocalHashCode & (table.length - 1);
Entry e = table[i];
if (e != null && e.get() == key)
return e;
else
return getEntryAfterMiss(key, i, e);
}
InheritableThreadLocal
暂无
先简单实现一个由ThreadLocal管理的类
public class StudentThreadLocal {
public static final ThreadLocal<Student> studentLocal = new InheritableThreadLocal<Student>();
public void init() {
if(studentLocal.get()!=null) {
return;
}else {
studentLocal.set(new Student());
}
}
public void setName(String name) {
studentLocal.get().setName(name);
}
public String getName() {
return studentLocal.get().getName();
}
}
测试
public static void main(String[] args) throws InterruptedException {
StudentThreadLocal studentThreadLocal = new StudentThreadLocal();
studentThreadLocal.init();
studentThreadLocal.setName("马化腾");
System.out.println(studentThreadLocal.getName());
Thread thread=new Thread(new Runnable() {
public void run() {
StudentThreadLocal studentThreadLocal = new StudentThreadLocal();
studentThreadLocal.init();
studentThreadLocal.setName("马匹");
}
});
thread.start();
Thread.sleep(200);
System.out.println(studentThreadLocal.getName());
}
输出结果:
马化腾
马匹
可以发现都是同一个ThreadLocal,因为使用的是InheritableThreadLocal
同样,换一个线程测试一下,先让下面的方法先运行,在运行上一个
public static void main(String[] args) throws InterruptedException {
StudentThreadLocal studentThreadLocal=new StudentThreadLocal();
studentThreadLocal.init();
studentThreadLocal.setName("sdasadsa");
Thread.sleep(5000);
System.out.println(studentThreadLocal.getName());
}
输出结果:
马化腾
马匹
发现每个线程都有自己独立管理的ThreadLocal