/** * 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. */ staticclassEntryextendsWeakReference<ThreadLocal<?>> { /** * The value associated with this ThreadLocal. */ Object value;
/** * Returns the value in the current thread's copy of this * thread-local variable. If the variable has no value for the * current thread, it is first initialized to the value returned * by an invocation of the {@link #initialValue} method. * 返回当前线程的内部变量副本,如果没有就返回变量的初始值 * * @return the current thread's value of this thread-local */ public T get() { //获取当前线程 Threadt= Thread.currentThread(); //获取此线程相关联的ThreadLocal,entry的key为WeakReference,值为强引用,注意内存溢出。 ThreadLocalMapmap= getMap(t); //如果存在值,就返回 if (map != null) { ThreadLocalMap.Entrye= map.getEntry(this); if (e != null) { @SuppressWarnings("unchecked") Tresult= (T) e.value; return result; } } //不存在就返回初始值,并设置ThreadLocalMap映射 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() { //获取初始值 Tvalue= initialValue(); //当前线程 Threadt= Thread.currentThread(); //获取当前线程映射 ThreadLocalMapmap= getMap(t); //有的话就设置初始值,没有的话新建map if (map != null) map.set(this, value); else createMap(t, value); //返回初始值 return value; }
set()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/** * Sets the current thread's copy of this thread-local variable * to the specified value. Most subclasses will have no need to * override this method, relying solely on the {@link #initialValue} * method to set the values of thread-locals. * * @param value the value to be stored in the current thread's copy of * this thread-local. */ publicvoidset(T value) { Threadt= Thread.currentThread(); ThreadLocalMapmap= getMap(t); if (map != null) map.set(this, value); else createMap(t, value); }