ThreadLocal

我们开启源码模式,JDK6与JDK7实现有些区别,不过思想是一样的.这边使用JDK7的源码

/**
* 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.
*/
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}

ThreadLocalMap

可以再看看,这个ThreadLocalMap类:

staticclassThreadLocalMap{/**
* 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. */Objectvalue;Entry(ThreadLocalk,Objectv){super(k);value=v;}}/**
* The initial capacity -- MUST be a power of two.
*/privatestaticfinalintINITIAL_CAPACITY=16;/**
* Set the value associated with key.
*
* @param key the thread local object
* @param value the value to be set
*/privatevoidset(ThreadLocalkey,Objectvalue){// 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....if(!cleanSomeSlots(i,sz)&&sz>=threshold)rehash();}