首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ConcurrentHashMap放置

ConcurrentHashMap放置
EN

Stack Overflow用户
提问于 2016-06-04 09:48:40
回答 3查看 316关注 0票数 0

我有一张地图

代码语言:javascript
复制
ConcurrentMap<K, V> myMap = new ConcurrentHashMap<>();

现在我想用原子的方式将新的对象插入到地图中,这样我就可以做如下的事情

代码语言:javascript
复制
V myMethod(K key, int val) {
    return map.putIfAbsent(key, new V(val));
}

但是它不是原子的,因为首先会产生新的V,然后插入到地图中。在不使用同步(或者使用同步是这里最快的方法)的情况下,有什么方法可以做到这一点吗?

EN

回答 3

Stack Overflow用户

发布于 2016-06-04 09:52:22

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

代码语言:javascript
复制
/*
 * 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;
}

代码语言:javascript
复制
 * 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

票数 1
EN

Stack Overflow用户

发布于 2016-06-04 10:13:16

您似乎在寻找Java8中的computeIfAbsent。

代码语言:javascript
复制
V myMethod(K key, int val) {
    return map.computeIfAbsent(key, () -> new V(val));
}

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

票数 0
EN

Stack Overflow用户

发布于 2016-06-04 11:06:42

Javadoc显式地声明putIfAbsent() 原子。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37628782

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档