HashMap 1 8 原始碼解析以及非執行緒安全分析

2021-09-08 11:40:02 字數 2034 閱讀 9290

程式設計師們,在北上廣你還能買房嗎? >>>

1、首先看下hashmap的put方法。

final v putval(int hash, k key, v value, boolean onlyifabsent,

boolean evict)

if (e.hash == hash &&

((k = e.key) == key || (key != null && key.equals(k))))

break;

p = e;}}

v oldvalue = e.value;

if (!onlyifabsent || oldvalue == null)

e.value = value;

afternodeaccess(e);

return oldvalue;}}

++modcount;

// 當map中的資料大於16*0.75=12 map的初始化大小位16,負載因子0.75

if (++size > threshold)

resize();

afternodeinsertion(evict);

return null;

}

public synchronized v put(k key, v value) 

// makes sure the key is not already in the hashtable.

entry,?> tab = table;

int hash = key.hashcode();

int index = (hash & 0x7fffffff) % tab.length;

@suppresswarnings("unchecked")

entryentry = (entry)tab[index];

for(; entry != null ; entry = entry.next)

}addentry(hash, key, value, index);

return null;

}

3、 當前有辦法了,concurrenthashmap閃亮登場

/** implementation for put and putifabsent */

final v putval(k key, v value, boolean onlyifabsent)

else if ((fh = f.hash) == moved)

// 此處map擴容後,資料轉移

tab = helptransfer(tab, f);

else

nodepred = e;

if ((e = e.next) == null) }}

else if (f instanceof treebin) }}

}if (bincount != 0) }}

addcount(1l, bincount);

return null;

}

4、回到剛才concurrentmap初始化 tab = inittable()

private transient volatile int sizectl; // 注意此處sizectl為volatile

private final node inittable()

} finally

break;}}

return tab;

}

5、concurrentmap擴容注意點

concurrentmap擴容時,其他執行緒不能再往map中新增/刪除資料了,那麼難道其他執行緒在那邊等待,直到擴容完成?當然不是了,其他執行緒會去幫助擴容執行緒一起進行擴容,每個執行緒都會去領取屬於自己的任務

final node helptransfer(node tab, nodef) 

}return nexttab;

}return table;

}

HashMap1 8原始碼分析

1 hashmap的原理,內部資料結構如何?底層使用雜湊表 陣列 鍊錶 當鍊表過長 其實是大於8 的時候會將鍊錶轉換成紅黑樹,以實現n log n 的查詢。2 具體過程 對 key 求 hash 值,然後再計算 下標。如果沒有碰撞,直接放入桶中,如果碰撞了,以鍊錶的方式鏈結到後面,如果鍊錶長度超過閥...

HashMap 1 8 原始碼閱讀

一 初始化 1.無參建構函式 負載因子預設值 static final float default load factor 0.75f 指定loadfactor負載因子的值是0.75f public hashmap 2.指定初始化大小和負載因子 hashmap的最大容量 static final i...

原始碼分析 HashMap 1 8

1.0 資料結構 2.0 儲存流程 3.0 陣列元素 鍊錶節點的實現類 hashmap中的陣列元素 鍊錶節點 採用node類 實現,與jdk1.7相比只是把entry換了個名字 hashmap中的紅黑樹節點 採用treenode類 實現 紅黑樹節點 實現類 繼承自linkedhashmap.entr...