正如紀錄片中所說的,「這段代碼濫用loadFactor字段來執行double-duty作爲正在進行中的hashCode標誌,所以沒有惡化空間性能。負載因子表明散列碼計算正在進行中。「 如何理解這一段?如何理解JDK的源代碼中的java.util.Hashtable的hashCode函數
public synchronized int hashCode() {
/*
* This code detects the recursion caused by computing the hash code
* of a self-referential hash table and prevents the stack overflow
* that would otherwise result. This allows certain 1.1-era
* applets with self-referential hash tables to work. This code
* abuses the loadFactor field to do double-duty as a hashCode
* in progress flag, so as not to worsen the space performance.
* A negative load factor indicates that hash code computation is
* in progress.
*/
int h = 0;
if (count == 0 || loadFactor < 0)
return h; // Returns zero
loadFactor = -loadFactor; // Mark hashCode computation in progress
Entry[] tab = table;
for (int i = 0; i < tab.length; i++)
for (Entry e = tab[i]; e != null; e = e.next)
h += e.key.hashCode()^e.value.hashCode();
loadFactor = -loadFactor; // Mark hashCode computation complete
return h;
您試圖解決什麼問題? –
Thranks for your help.I只讀源代碼,無法理解爲什麼作者使用loadFactor作爲hashcode的計算進度中的一個標誌。設置此標誌的含義是什麼?此函數是自身同步的,因此它的線程安全,不是嗎? –
這不是一個線程問題。例如,如果例如循環將發生。 'e.value'指向與'this'相同的散列表。即使只有一個線程,也會發生這種情況,正如@Jasper所指出的那樣,如果沒有檢測到它會導致堆棧溢出。 –