一、糟糕的面试
面试官:小王,你说说HashMap的是线程安全的吗?
小王:HashMap不安全,在多线程下,会出现线程安全问题。他兄弟HashTable
线程是安全的,但是出于性能考虑,我们往往会选择ConcurrentHashMap。
面试官:HashMap线程不安全的原因是什么?
小王:这个…暂时忘记了
面试官:为什么HashTable线程安全,为什么性能低?
小王:这个…
面试官:ConcurrentHashMap是怎么实现线程安全的?性能为什么较高?
小王:…
面试官:回答的很不错,回去等通知吧。
二、hashMap
2.1 暴露问题
大家都知道,HashMap在多线程下会存在线程安全问题,如下:
public class Demo2 {
public static void main(String[] args) {
//shift+ctrl+alt+u
HashMap<String, String> map = new HashMap<>();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i <= 10; i++) {
map.put(i+"",i+"");
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 11; i <= 20; i++) {
map.put(i+"",i+"");
}
}
});
t1.start();
t2.start();
//确保两个子线程执行完毕之后,主线程再来打印hashmap
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//遍历hashMap
for (int i = 1; i <= 20; i++) {
System.out.println(map.get(i + ""));
}
}
}
控制台:
null
2
null
null
null
6
7
8
9
10
null
null
13
null
null
null
17
18
19
20
以上例子证明了,HashMap确实存在线程安全问题。
2.2 源码追踪
翻阅源码(1.8)如下:
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;
}
(1)代码一
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
是否Hash冲突,没冲突就直接赋值给数组当前索引。
线程A判断通过,进入方法,切换B线程,判断通过,进入方法,切换A线程,赋值成功,切换B线程赋值成功,B线程的值覆盖了A线程的值,发生了数据覆盖,用户感受到是数据丢失。
(2) 代码二
if (++size > threshold)
resize();
当元素个数size大于扩容阈值,则扩容,这里会有两个问题。
- 成员的size变量没有保证原子性,因此多线程下size自增是存在原子性问题。即添加了两个元素,但是size只增加了1。
- 两个线程如果都通过上面阈值的判断,就会发生扩容两次的情况,这也是一种安全问题。