HashMap 源码分析
工作5年,之前一直看不懂hashMap 源码,前几天面试有问到,此片博客记录下本人40 分钟研究的源码想法(本文基于jdk1.8),HashMap 的底层常说是数组加链表。
- hashMap 的 put 方法
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//判断数组是否有初始化,没有就初始化数组
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//判断数组的最后一个或者 经过hash 散列算法的数组位置值是否为空,为空则将 值 放在该数组处
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
// 在hash值相等的情况下和key 相等的情况下,替换k,v
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//这个题主暂未做深入分析
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
// 遍历链表,将值放在链表的后一位 既next
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//链表中key 存在了,hash 值也相等,替换存在的k,v
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
关于hashMap 的线程不安全,如下示例
package com.pingan.test;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class ThreadLock {
public static Map map = new HashMap<>();
public ThreadLock() {
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 500; i++) {
map.put(new Integer(i), i);
}
System.out.println("thread1 over");
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 500; i < 1000; i++) {
map.put(new Integer(i), i);
}
System.out.println("thread2 over");
}
});
thread1.start();
thread2.start();
}
public static void main(String[] args) throws InterruptedException {
new ThreadLock();
Thread.currentThread().sleep(1000);
System.out.println("res: " + map.size());
int res = 0;
Iterator iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Integer, Integer> next = (Map.Entry<Integer, Integer>) iterator.next();
res++;
System.out.println("key: " + next.getKey() + " =v: " + next.getValue() + " ==" + (next.getKey().equals(next.getValue())));
}
System.out.println("len: " + res + " result: " + map.get(2));
}
}
可以看到 里边关于 0-20 的key 基本消失,被覆盖了,并且整个map 的长度本应该是1000,然而只有955。
现在着重看不安全的代码处(分析put 方法)
// 当此处存在hash 冲突的时候,两个线程同时将值放入此处,则有一个值必然被覆盖
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
不安全二
在多线程遍历链表的时候会存在多个线程插入同一node 的情况,从而造成 值的覆盖
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}