Java基础「1」

HashMap vs ConcurrentHashMap vs HashTable

Posted by Jie on February 22, 2017

线程安全

HashMap

初始化

//jdk1.8
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
// jdk1.7
this.loadFactor = loadFactor;
threshold = initialCapacity;

1.8阈值都是2的平方,而且1.8桶里面会进化为红黑树,1.7一直是链表。

HashMap不是线程安全,会导致数据不一致和死循环(resize)。

ConcurrentHashMap

LOAD_FACTOR 写死了, 使用unsafe直接读写既提高效率,也是原子操作,保证线程安全。

put的时候每个桶一个锁。

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;

            // table不存在
            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
            }
            // 扩容后正在转移数据,加入转移过程
            // 转移的时候table中head节点为ForwardingNode,hash就为moved
            else if ((fh = f.hash) == MOVED)
                tab = helpTransfer(tab, f);
            else {
                V oldVal = null;
                synchronized (f) {
                    // 为了线程安全还需要if
                    if (tabAt(tab, i) == f) {
                        // 红黑树的hash=-2
                        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) {
                    // 转为红黑树
                    if (binCount >= TREEIFY_THRESHOLD)
                        treeifyBin(tab, i);
                    if (oldVal != null)
                        return oldVal;
                    break;
                }
            }
        }
        // 增加元素个数,并判断扩容
        addCount(1L, binCount);
        return null;
    }

但是当桶为空的时候,没有加锁,这时候如果多线程,并且多个key分到这个桶,线程不安全?

 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
            }
static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,
                                        Node<K,V> c, Node<K,V> v) {
        return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
    }

https://en.wikipedia.org/wiki/Compare-and-swap CAS是硬件层面的原子操作,其实还是安全。

扩容的时候死循环?

扩容分两步,生成新的容器和移动元素。

只能有一个线程对容器扩容,但是可以多个线程转移元素,转移的时候,线程都会对桶上锁。

所以不会发生类似HashMap的死循环。

所以只需要注意程序的线程安全

下面这种可能就不是想要的结果

if (!map.containsKey(key))
   return map.put(key, value);
else
   return map.get(key);

这种情况就直接使用onlyIfAbsent方法

Hashtable

put方法直接被synchronized