HashMap不是线程安全的,在并发条件下,当线程A执行put方法插入数据到HashMap中,在执行完下图中判断为空后,线程B抢占内存资源,在相同位置执行put方法插入数据。当线程A重新获得内存时,继续在原位置插入数据,造成线程B数据被覆盖。因此HashMap在并发情况下是线程不安全的。
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;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
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) {
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;
}
}
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内部也有fail-fast机制保障Iterator迭代器在遍历一个集合对象时如果遍历过程中对集合对象的内容进行了修改,会抛出Concurrent Modification Exception,但不能依赖此异常对hashmap进行并发操作。fail-fast机制通过modCount值记录实际修改hashmap的次数,在集合遍历时,通过比较modCount值来判断是否抛出异常,但是如果遍历时,集合发生变化时修改modCount值又设置为了expectedmodCount值,则异常不会抛出。
与之相比HashTable是线程安全的,它采用了fail-safe机制,使用CopyOnWriteArrayList方法拷贝当前数组,实现读写分离,同时对数据操作的时候都会上同步锁。但是HashTable效率比较低,一般不使用。
一般使用ConcurrentHashMap,ConcurrentHashMap在1.7以前采用了volatile分段锁修饰数据value和下一个节点next,从而保证集合元素有多少就能容纳多少容量的并发,在1.8后优化了数据结构,采用了CAS+synchronized来保证并发安全性,CAS在读取数据时不加锁,在准备回写数据时,比较原值是否被修改,若未修改则写回,修改了则重新执行读取流程。在CAS写入失败的时候会采用synchronized,且此synchronized也是已经优化过的,逐步升级到重量级锁的synchronized。