求求你!别再这样用 HashMap 了好吗?
开发者技术前线
共 5870字,需浏览 12分钟
·
2020-09-28 23:03
点击“开发者技术前线”,选择“星标?”
在看|星标|留言, 真爱
1.jdk1.7中的HashMap
1 public class HashMapTest {
2
3 public static void main(String[] args) {
4 HashMapThread thread0 = new HashMapThread();
5 HashMapThread thread1 = new HashMapThread();
6 HashMapThread thread2 = new HashMapThread();
7 HashMapThread thread3 = new HashMapThread();
8 HashMapThread thread4 = new HashMapThread();
9 thread0.start();
10 thread1.start();
11 thread2.start();
12 thread3.start();
13 thread4.start();
14 }
15 }
16
17 class HashMapThread extends Thread {
18 private static AtomicInteger ai = new AtomicInteger();
19 private static Mapmap = new HashMap<>();
20
21 @Override
22 public void run() {
23 while (ai.get() < 1000000) {
24 map.put(ai.get(), ai.get());
25 ai.incrementAndGet();
26 }
27 }
28 }
1 void transfer(Entry[] newTable, boolean rehash) {
2 int newCapacity = newTable.length;
3 for (Entrye : table) {
4 while(null != e) {
5 Entrynext = e.next;
6 if (rehash) {
7 e.hash = null == e.key ? 0 : hash(e.key);
8 }
9 int i = indexFor(e.hash, newCapacity);
10 e.next = newTable[i];
11 newTable[i] = e;
12 e = next;
13 }
14 }
15 }
1.1 扩容造成死循环分析过程
newTable[3]=e ----> newTable[3]=3
e=next ----> e=7
e=7
next=e.next ----> next=3【从主存中取值】
e.next=newTable[3] ----> e.next=3【从主存中取值】
newTable[3]=e ----> newTable[3]=7
e=next ----> e=3
e=3
next=e.next ----> next=null
e.next=newTable[3] ----> e.next=7 即:3.next=7
newTable[3]=e ----> newTable[3]=3
e=next ----> e=null
1.2 扩容造成数据丢失分析过程
e=5
next=e.next ----> next=null,从主存中取值
e.next=newTable[1] ----> e.next=5,从主存中取值
newTable[1]=e ----> newTable[1]=5
e=next ----> e=null
2.jdk1.8中HashMap
1 final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
2 boolean evict) {
3 Node[] tab; Node p; int n, i;
4 if ((tab = table) == null || (n = tab.length) == 0)
5 n = (tab = resize()).length;
6 if ((p = tab[i = (n - 1) & hash]) == null) // 如果没有hash碰撞则直接插入元素
7 tab[i] = newNode(hash, key, value, null);
8 else {
9 Nodee; K k;
10 if (p.hash == hash &&
11 ((k = p.key) == key || (key != null && key.equals(k))))
12 e = p;
13 else if (p instanceof TreeNode)
14 e = ((TreeNode)p).putTreeVal(this, tab, hash, key, value);
15 else {
16 for (int binCount = 0; ; ++binCount) {
17 if ((e = p.next) == null) {
18 p.next = newNode(hash, key, value, null);
19 if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
20 treeifyBin(tab, hash);
21 break;
22 }
23 if (e.hash == hash &&
24 ((k = e.key) == key || (key != null && key.equals(k))))
25 break;
26 p = e;
27 }
28 }
29 if (e != null) { // existing mapping for key
30 V oldValue = e.value;
31 if (!onlyIfAbsent || oldValue == null)
32 e.value = value;
33 afterNodeAccess(e);
34 return oldValue;
35 }
36 }
37 ++modCount;
38 if (++size > threshold)
39 resize();
40 afterNodeInsertion(evict);
41 return null;
42 }
总结
开发者技术前线 ,汇集技术前线快讯和关注行业趋势,大厂干货,是开发者经历和成长的优秀指南。
评论