/** * 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){ Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); }
/** * 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; } /** * Create the map associated with a ThreadLocal. Overridden in * InheritableThreadLocal. * @param t the current thread * @param firstValue value for the initial entry of the map * @param map the map to store. */ voidcreateMap(Thread t, T firstValue){ t.threadLocals = new ThreadLocalMap(this, firstValue); }
接下来再看一下ThreadLocal类中的get()方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/** * 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(){ 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(); }
再来看setInitialValue()方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/** * 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; }