參考(感謝以下大佬):
http://blog.csdn.net/qq_27093465/article/details/52207135
http://blog.csdn.net/u011392897/article/details/57105709
http://www.cnblogs.com/ygj0930/p/6543350.html
http://blog.csdn.net/u011392897/article/details/57115818
http://blog.csdn.net/u011392897/article/details/60141790
http://blog.csdn.net/u011392897/article/details/60149314
https://coolshell.cn/articles/9606.html
https://www.cnblogs.com/woshimrf/p/hashmap.html
https://blog.csdn.net/qq_27093465/article/details/52207135
https://blog.csdn.net/hzw05103020/article/details/47207787
https://github.com/crossoverJie/Java-Interview/blob/master/MD/HashMap.md
JDK1.7的HashMap
以下基于 JDK1.7 分析。
初始化
如圖所示,HashMap 底層是基于數(shù)組和鏈表實(shí)現(xiàn)的。其中有兩個(gè)重要的參數(shù):
- 容量
- 負(fù)載因子
容量的默認(rèn)大小是 16,負(fù)載因子是 0.75,當(dāng) HashMap
的 size > 16*0.75
時(shí)就會(huì)發(fā)生擴(kuò)容resize(容量和負(fù)載因子都可以自由調(diào)整)。
//擴(kuò)容判斷值
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);//0.75*16
threshold = newThr;
//容量大于閥值,觸發(fā)resize
if (++size > threshold)
resize();
//新建數(shù)組
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
//后續(xù)是利用頭插法,將舊值賦值到新的數(shù)組去
put 方法
- 首先會(huì)將傳入的 Key 做
hash
運(yùn)算計(jì)算出 hashcode,然后根據(jù)數(shù)組長(zhǎng)度取模計(jì)算出在數(shù)組中的 index 下標(biāo)。
(由于在計(jì)算中位運(yùn)算比取模運(yùn)算效率高的多,所以 HashMap 規(guī)定數(shù)組的長(zhǎng)度為 2^n
。這樣用 2^n - 1
做位運(yùn)算與取模效果一致,并且效率還要高出許多。參考:https://blog.csdn.net/Feifan_Feimeng/article/details/71006015)
//源碼
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
//先獲取長(zhǎng)度:(tab = resize()).length
//再算出index:tab[i = (n - 1) & hash]
- 由于數(shù)組的長(zhǎng)度有限,所以難免會(huì)出現(xiàn)不同的 Key 通過運(yùn)算得到的 index 相同,這個(gè)就是hash沖突。
(這種情況可以利用鏈表來(lái)解決,HashMap 會(huì)在 table[index]
處形成鏈表,采用頭插法將數(shù)據(jù)插入到鏈表中。如:head --> 3 --> 7 --> 5)
get 方法
get 和 put 類似,也是將傳入的 Key 計(jì)算出 index ,如果該位置上是一個(gè)鏈表就需要遍歷整個(gè)鏈表,通過 key.equals(k)
來(lái)找到對(duì)應(yīng)的元素。(注意:這里使得HashMap的性能下降,從O(1)變成O(n))
遍歷 方法
Iterator<Map.Entry<String, Integer>> entryIterator = map.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<String, Integer> next = entryIterator.next();
System.out.println("key=" + next.getKey() + " value=" + next.getValue());
}
Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()){
String key = iterator.next();
System.out.println("key=" + key + " value=" + map.get(key));
}
map.forEach((key,value)->{
System.out.println("key=" + key + " value=" + value);
});
強(qiáng)烈建議使用第一種 EntrySet 進(jìn)行遍歷。
- 第一種可以把 key value 同時(shí)取出;
- 第二種還得需要通過 key 取一次 value,效率較低,;
- 第三種需要
JDK1.8
以上,通過外層遍歷 table,內(nèi)層遍歷鏈表或紅黑樹。
缺點(diǎn)
- 缺點(diǎn)1:數(shù)據(jù)量大的時(shí)候?qū)е骂l繁擴(kuò)容,效率降低
- 缺點(diǎn)2:數(shù)據(jù)量大的時(shí)候,hash取模沖突導(dǎo)致鏈表過長(zhǎng),O(1)變成O(n)
- 缺點(diǎn)3:線程不安全,會(huì)出現(xiàn)循環(huán)鏈表導(dǎo)致線程死循環(huán)
JDK1.8中HashMap的改進(jìn)
針對(duì)上述的HashMap的三個(gè)缺點(diǎn),JDK1.8該如何解決?
1.擴(kuò)容效率低怎么辦?
沒解決!
新版的依然是:容量的默認(rèn)大小是 16,負(fù)載因子是 0.75,達(dá)到閥值依然執(zhí)行resize()。
依然是新增一個(gè)數(shù)組,損耗依然存在!
2.hash取模沖突導(dǎo)致鏈表過長(zhǎng),O(1)變成O(n)怎么辦?
//Node鏈表的容量大于8的時(shí)候,觸發(fā)使用紅黑樹存儲(chǔ)
static final int TREEIFY_THRESHOLD = 8;
if (binCount >= TREEIFY_THRESHOLD - 1)
treeifyBin(tab, hash);
//不用鏈表存儲(chǔ)了,用紅黑樹存儲(chǔ)
/**
* Replaces all linked nodes in bin at index for given hash unless
* table is too small, in which case resizes instead.
*/
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
else if ((e = tab[index = (n - 1) & hash]) != null) {
TreeNode<K,V> hd = null, tl = null;
do {
TreeNode<K,V> p = replacementTreeNode(e, null);
if (tl == null)
hd = p;
else {
p.prev = tl;
tl.next = p;
}
tl = p;
} while ((e = e.next) != null);
if ((tab[index] = hd) != null)
hd.treeify(tab);
}
}
Node中鏈表長(zhǎng)度大于8,就轉(zhuǎn)成紅黑樹存儲(chǔ)了,當(dāng)然舊數(shù)據(jù)也會(huì)放到紅黑樹里面。
同時(shí),最差速度到達(dá)了O(log(n)),快了!
3.線程不安全,會(huì)出現(xiàn)循環(huán)鏈表導(dǎo)致線程死循環(huán)怎么辦?
官方的回復(fù)是:線程安全請(qǐng)使用ConcurrentHashMap,HashMap本身就是線程不安全的。
但是雖然HashMap依然是線程不安全,但是1.8將不會(huì)出現(xiàn)死循環(huán)的情況了。原因如下:
- 1.7中擴(kuò)容,復(fù)制數(shù)組使用的是頭插法,原本1-2-3的鏈表會(huì)變成3-2-1,所以多線程下容易出現(xiàn)2-3和3-2的情況導(dǎo)致死循環(huán),在查詢一個(gè)不存在的key時(shí),死循環(huán)沒辦法跳出導(dǎo)致CPU100%!??!
- 1.8的擴(kuò)容中,使用的是尾插法,因此哪怕是多線程下,也不會(huì)出現(xiàn)死循環(huán)。
4.解決了1.7中Hash攻擊導(dǎo)致的CPU100%
參考:
https://www.cnblogs.com/stevenczp/p/7028071.html
https://blog.csdn.net/zly9923218/article/details/51656920
https://coolshell.cn/articles/6424.html
首先我們需要知道的是:
Java的hash算法是“非隨機(jī)的”,是固定的,而且是弱化的,容易相同!
比如:
- Aa和BB這兩個(gè)字符串的hash code(或hash key) 是一樣的!
- 同理,我們就可以通過這兩個(gè)種子生成更多的擁有同一個(gè)hash key的字符串:”AaAa”, “AaBB”, “BBAa”, “BBBB”,“AaAaBBBB”...
System.out.println("AaAaAaAa".hashCode());
System.out.println("AaAaBBBB".hashCode());
-540425984
-540425984
相同的hash值意味著相同的index,那么在hashMap中就是會(huì)建立N長(zhǎng)的鏈表
因此:JDK1.7中會(huì)有Hash Collision DoS的攻擊,鏈表無(wú)限長(zhǎng),循環(huán)進(jìn)行equal的時(shí)候損耗極大,以至于CPU100%!
JDK1.8中針對(duì)Hash攻擊做了處理!
public class Person implements Comparable<Person>{
private String firstName;
private String lastName;
private UUID id;
public Person(String firstName, String lastName, UUID id) {
this.firstName = firstName;
this.lastName = lastName;
this.id = id;
}
@Override
public int hashCode() {
return 5;
}
@Override
public int compareTo(Person o) {
return this.id.compareTo(o.id);
}
// ...
}
@Test
public void hashMap1_8() throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
int LIMIT = 500_000;
Person person = null;
Map<Person, String> map = new HashMap<>();
for (int i=0;i<LIMIT;i++) {
UUID randomUUID = UUID.randomUUID();
person = new Person("fn", "ln", randomUUID);
map.put(person, "comment" + i);
}
long start = System.currentTimeMillis();
map.get(person);
long stop = System.currentTimeMillis();
System.out.println(stop-start+" millis");
}
上述代碼在1.8的測(cè)試下,加了Comparable接口的情況下,get/set的速度得到了極大的提升!
但是如果不加Comparable接口,1.8下將會(huì)觸發(fā)自己的對(duì)比判斷,而這個(gè)判斷是比較對(duì)象類型和hashcode,所以會(huì)降低速度,但是不會(huì)像JDK1.7那樣導(dǎo)致鏈表過長(zhǎng)而引起的CPU100%。
參考:https://blog.csdn.net/weixin_42340670/article/details/80673127
if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0)
dir = tieBreakOrder(k, pk);
總結(jié)如下:
JDK1.7 + 大量hash沖突的情況下:導(dǎo)致CPU100%
JDK1.8 + 大量hash沖突的情況下 + 實(shí)現(xiàn)Comparable接口:get/set速度極快,500萬(wàn)下沖突數(shù)據(jù)都能在毫秒級(jí)別響應(yīng)
JDK1.8 + 大量hash沖突的情況下+ 不實(shí)現(xiàn)Comparable接口:get/set速度很慢,因?yàn)闆_突多會(huì)執(zhí)行內(nèi)部實(shí)現(xiàn)的對(duì)比代碼,導(dǎo)致get/set速度降低,但是不會(huì)像JDK1.7那樣導(dǎo)致鏈表過長(zhǎng)而引起CPU100%。