前情提要:
并发条件下向set中放数据(此操作不规范哈,小伙伴切勿模仿,如果要并发下Set的话,推荐使用线程安全的 同步容器类 或者 并发容器类),HashSet中的元素数和其size()的结果不一致。
思考过程:
1、咱们都知道,HashSet 底层是 HashMap实现的,而HashMap是线程不安全的。所以问题肯定是出在了线程不安全上。虽说是知道了问题出在线程不安全上,咱也得打破沙锅问一问,到底是哪块代码出了问题。
2、既然是确定是线程不安全,那么问题大概率是出现在了新增上。因并发新增所引发。
3、接下来咱们追源码。
源码如下:HashSet.add调用的是HashMap.put
HashSet.add源码:
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
HashMap.put源码
/**
* Implements Map.put and related methods
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
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;
}
上面的代码比较长,有兴趣的小伙伴可以仔细阅读,着急的小伙伴可以直接跳过。
关键代码:
//重点看if这块代码;
if ((p = tab[i = (n - 1) & hash]) == null)
//table[i]上没有元素,那么new一个节点出来
tab[i] = newNode(hash, key, value, null);
else
//重复元素进入时会return掉,不会改变size大小
...
...
...
//上诉进入if,new了新节点后,接下来便执行了如下代码
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
看到这,相信小伙伴们就明白问题所在了。
yes!!!你想的没有错 !!!
就是因为,在并发环境下,首次创建节点时的判断在多线程的环境下是不安全的,所以导致多个线程同时被认定为首次创建节点,从而跳过了else判重环节,最终走到了++size那,导致size加多了。