1.首先如果让我们设计这种结构,我们怎么设计?
因为threadlocal从功能上看是每个线程都有独立的副本,互不影响,在自己各自的栈中。如果我们设计的话,肯定想到是跟每个线程有关系。然后每个线程又关联一个具体的值,这样很容易让我们想到hashmap这种数据结构。以thread为key,以我们要的值,为value。在多线程中,我们可能想到线程安全的hashmap,concurrenthashmap这种。然而threadlocal并不是这种设计的,但是与这思想很类似。
2.我们看一下threadlocal的get和set方法
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null)
return (T)e.value;
}
return setInitialValue();
}
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null)
return (T)e.value;
}
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;
}
T value = initialValue();
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
return value;
}
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
为什么通过t获取map哪?而不是直接用map哪?首先这个map具体变量entry继承了WeakReference能帮助尽快释放内存。另外是因为我们看到根据t获取map。
以上只是本人自己的理解,如果错误,敬请谅解。