publicTget() {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; } }returnsetInitialValue();}publicvoidset(T value) {Thread t =Thread.currentThread();ThreadLocalMap map =getMap(t);if (map !=null) {map.set(this, value); } else {createMap(t, value); }}voidcreateMap(Thread t,T firstValue) {t.threadLocals=newThreadLocalMap(this, firstValue);}
ThreadLocalMap.class
staticclassEntryextendsWeakReference<ThreadLocal<?>> { /** The value associated with this ThreadLocal. */Object value;Entry(ThreadLocal<?> k,Object v) { super(k); value = v; }}privateEntry[] table;privateEntrygetEntry(ThreadLocal<?> key) {int i =key.threadLocalHashCode& (table.length-1);Entry e = table[i];if (e !=null&&e.get() == key)return e;elsereturngetEntryAfterMiss(key, i, e);}privatevoidset(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] =newEntry(key, value);int sz =++size;if (!cleanSomeSlots(i, sz)&& sz >= threshold)rehash();}