我有一张地图
ConcurrentMap<K, V> myMap = new ConcurrentHashMap<>();现在我想用原子的方式将新的对象插入到地图中,这样我就可以做如下的事情
V myMethod(K key, int val) {
return map.putIfAbsent(key, new V(val));
}但是它不是原子的,因为首先会产生新的V,然后插入到地图中。在不使用同步(或者使用同步是这里最快的方法)的情况下,有什么方法可以做到这一点吗?
发布于 2016-06-04 09:52:22
但是..。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。
发布于 2016-06-04 10:13:16
您似乎在寻找Java8中的computeIfAbsent。
V myMethod(K key, int val) {
return map.computeIfAbsent(key, () -> new V(val));
}这将只创建每个键一次的V对象。注意:它仍然会每次创建一个lambda对象(除非Escape Analysis将它放在堆栈上)
发布于 2016-06-04 11:06:42
Javadoc显式地声明putIfAbsent() 是原子。
https://stackoverflow.com/questions/37628782
复制相似问题