/** Implementation for put and putIfAbsent */
final V putVal(K key, V value, boolean onlyIfAbsent) {
if (key == null || value == null) throw new NullPointerException();
int hash = spread(key.hashCode());
int binCount = 0;
for (Node<K,V>[] tab = table;;) {
Node<K,V> f; int n, i, fh;
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, null)))
break; // no lock when adding to empty bin
}
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
else {
V oldVal = null;
synchronized (f) {
if (tabAt(tab, i) == f) {
if (fh >= 0) {
在上面的这里:
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
if (casTabAt(tab, i, null,
new Node<K,V>(hash, key, value, null)))
break; // no lock when adding to empty bin
}
如果有多个线程都要插入一个值,且值的hash一样,且都恰好进入了else if语句,那么由于cas的特性只会有一个线程会执行成功,但是由于在if语句里写死了判断的值为null,所以另一个值该如何呢?由于已经进入了else if语句那么下面的else语句是进入不了的,那么此时按照逻辑会出现只会有一个值的情况,另一个值被抛弃了。
看到这里觉得自己看到了jdk1.8的bug,兴奋不已,赶紧写一个博客压压惊,但是在写的过程中突然意识到一个问题就是,这个没有匹配到的线程是如何向下执行的,直接结束了还是什么,然后。。。。。。,mdzz
外面是一个死循环。。。。。。
也就是没有匹配到的线程会再次查找,这一次会匹配到else里,然后拿去链表头对象作为Synchronized,锁住链表然后执行添加操作。
在这里明白了ConcurrentHashMap的底层了,在空值时使用cas,因为如果使用synchronized必然要锁一个对象,但是无论如何做都会使得多个线程使用的是统一锁,此时这多个线程可能操控的是数组中的不同的位置,相当于锁的是整个数组,没有意义。但是使用cas就不一样了,因为此时就两个判断,要么为空要么不为空。所以cas在空值时使用,但是对于有节点的就不太行了,甚至于开销会更大即占cpu资源太多,此时使用synchronized较为合适。