【问题标题】:ConcurrentHashMap putConcurrentHashMap 放
【发布时间】:2016-06-04 09:48:40
【问题描述】:

我有以下地图

ConcurrentMap<K, V> myMap = new ConcurrentHashMap<>();

现在我想以原子方式将新对象插入到该映射中,所以我可以做类似的事情

V myMethod(K key, int val) {
    return map.putIfAbsent(key, new V(val));
}

但它不是原子的,因为首先会创建新的 V,然后将其插入到 map 中。有什么方法可以在不使用 synchronized 的情况下做到这一点(或者使用 synchronized 是这里最快的方法)?

【问题讨论】:

标签: concurrency


【解决方案1】:

但是...ConcurrentHashMap 已经在内部使用了同步。

/*
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * Written by Doug Lea with assistance from members of JCP JSR-166
 * Expert Group and released to the public domain, as explained at
 * http://creativecommons.org/publicdomain/zero/1.0/
 */

/** 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) {
                        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;
}

 * Insertion (via put or its variants) of the first node in an
 * empty bin is performed by just CASing it to the bin.  This is
 * by far the most common case for put operations under most
 * key/hash distributions.  Other update operations (insert,
 * delete, and replace) require locks.  We do not want to waste
 * the space required to associate a distinct lock object with
 * each bin, so instead use the first node of a bin list itself as
 * a lock. Locking support for these locks relies on builtin
 * "synchronized" monitors.

您不需要自己指定synchronized

【讨论】:

    【解决方案2】:

    看来您正在寻找 Java 8 中的 computeIfAbsent。

    V myMethod(K key, int val) {
        return map.computeIfAbsent(key, () -> new V(val));
    }
    

    这只会为每个键创建一次V 对象。注意:它每次仍然会创建一个 lambda 对象(除非 Escape Analysis 将它放在堆栈上)

    【讨论】:

    • @jpos 但您可以认为它已添加到 Java 8 中,因为在 Java 7 中没有简单的方法来执行此操作。注意:Java 7 已经结束公共更新一年多了.
    【解决方案3】:

    Javadoc 明确指出putIfAbsent() 原子的。

    【讨论】:

      猜你喜欢
      • 2022-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多