public T get(){ 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; } } return setInitialValue(); } //ThreadLocalMap中的getEntry方法 //首先进行Hash找到entry,如果发现key和我们的不同,那就是发生了两种情况 //第一种是已经被GC清除了,或者产生了冲突,这时候我们调用getEntryAfterMiss方法。 private Entry getEntry(ThreadLocal<?> key){ int i = key.threadLocalHashCode & (table.length - 1); Entry e = table[i]; if (e != null && e.get() == key) return e; else return getEntryAfterMiss(key, i, e); } private Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e){ Entry[] tab = table; int len = tab.length;
while (e != null) { ThreadLocal<?> k = e.get(); if (k == key) return e; //如果是被GC收集掉了,那么调用expungeStaleEntry方法把后面的重新Hash if (k == null) expungeStaleEntry(i); else //不然就是继续找下一个桶。 i = nextIndex(i, len); e = tab[i]; } returnnull; }
privateintexpungeStaleEntry(int staleSlot){ Entry[] tab = table; int len = tab.length;
Related Issues not found
Please contact @zhyzhyzhy to initialize the comment