/** * 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(); //获取当前线程ThreadLocalMap ThreadLocalMapmap= getMap(t); if (map != null) //非空将当前的ThreadLocal作为键,value作为值放进ThreadLocalMap里面 map.set(this, value); else //为空,创建一个ThreadLocalMap,再将值和键塞入map里面 createMap(t, 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() { //获取ThreadLocalMap Threadt= Thread.currentThread(); ThreadLocalMapmap= getMap(t); if (map != null) { 获得ThreadLocalMap中的Entry,也就是存放value值的一个对象 ThreadLocalMap.Entrye= map.getEntry(this); //不为空,取出这个值 if (e != null) { @SuppressWarnings("unchecked") Tresult= (T)e.value; return result; } } //为空,执行这个方法,将null写进ThreadLocalMap return setInitialValue(); }
private Entry getEntry(ThreadLocal<?> key) { inti= key.threadLocalHashCode & (table.length - 1); Entrye= table[i]; if (e != null && e.get() == key) return e; else return getEntryAfterMiss(key, i, e); }
staticclassEntryextendsWeakReference<ThreadLocal<?>> { /** The value associated with this ThreadLocal. */ Object value; Entry(ThreadLocal<?> k, Object v) { super(k); value = v; } }
/** * 进行扩容的阈值,表使用量大于它的时候进行扩容 */ privateint threshold; // Default to 0
存储结构
1 2 3 4 5 6 7 8
staticclassEntryextendsWeakReference<ThreadLocal<?>> { /** The value associated with this ThreadLocal. */ Object value; Entry(ThreadLocal<?> k, Object v) { super(k); value = v; } }