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) // 测试Hash碰撞
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 opublic V put(K key, V value) {
return putVal(key, value, false);
}
/** Implementation for put and putIfAbsent */
final V putVal(K key, V value, boolean onlyIfAbsent) {
if (key == null || value == null) throw new NullPointerException();
//1、计算出hash值
int hash = spread(key.hashCode());
int binCount = 0;
for (Node<K,V>[] tab = table;;) {
Node<K,V> f; int n, i, fh;
//2、判断当前数据结构是否从未放过数据,即是否未初始化,为空则先执行初始化
if (tab == null || (n = tab.length) == 0)
tab = initTable();
//3、通过key的hash判断当前位置是否为null
//(通过数组长度减一和hash做与运算得到要判断的当前数组位置)
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
//如果当前位置为null,则通过CAS写入,如果CAS写入失败,通过自旋保证写入成功
if (casTabAt(tab, i, null,
new Node<K,V>(hash, key, value, null)))
break; // no lock when adding to empty bin
}
//4、当前hash值等于MOVED(-1)时,需要进行扩容
else if ((fh = f.hash) == MOVED)
//扩容
tab = helpTransfer(tab, f);
else {
V oldVal = null;
//5、当上面的内容都不满足时,采用synchronized阻塞锁,来将数据进行写入
synchronized (f) {
if (tabAt(tab, i) == f) {
if (fh >= 0) {
binCount = 1;
for (Node<K,V> e = f;; ++binCount) {
K ek;
if (e.hash == hash &&
((ek = e.key) == key ||
(ek != null && key.equals(ek)))) {
oldVal = e.val;
if (!onlyIfAbsent)
e.val = value;
break;
}
Node<K,V> pred = e;
if ((e = e.next) == null) {
pred.next = new Node<K,V>(hash, key,
value, null);
break;
}
}
}
else if (f instanceof TreeBin) {
Node<K,V> p;
binCount = 2;
if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
value)) != null) {
oldVal = p.val;
if (!onlyIfAbsent)
p.val = value;
}
}
}
}
if (binCount != 0) {
//6、如果数量大于TREEIFY_THRESHOLD(8),需要转化为红黑树
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
}
}
addCount(1L, binCount);
return null;
}
两个线程同时向HashMap中put数据,若A线程执行完第6行时间片用完挂起,B线程获取CPU执行put操作,向HashMap中put了数据。之后A线程继续执行由于已经完成了Hash碰撞,会直接覆盖A线程的数据,造成数据不安全。
Node<K,V> f; int n, i, fh; K fk; V fv;
if (tab == null || (n = tab.length) == 0)
tab = initTable();
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
if (casTabAt(tab, i, null, new Node<K,V>(hash, key, value)))
break; // no lock when adding to empty bin
}
在ConCurrentHashMap中使用casTabAt方法中的Compare-And-Swap比较和交换方法保证线程安全
public final native boolean compareAndSetReference(Object o, long offset,
Object expected,
Object x);
对象 o 中偏移量为 offset 的引用字段的当前值与 expected 参数进行比较。如果两者相等,说明没有其他线程在此期间修改了该引用字段,那么方法会将该字段的值更新为 x 并返回 true。如果实际值与预期值不匹配(即有其他线程已更改了该引用),则不做任何改动,并返回 false。