ConcurrentHashMap

ConcurrentHashMap

A hash table supporting full concurrency of retrievals and high expected concurrency for updates.

ConcurrentMap

1
public interface ConcurrentMap<K, V> extends Map<K, V>{...}

A java.util.Map providing thread safety and atomicity guarantees.

Memory consistency effects( 内存一致性 ): As with other concurrent collections, actions in a thread prior to placing an object into a ConcurrentMap as a key or value happen-before actions subsequent to the access or removal of that object from the ConcurrentMap in another thread.

ConcurrentMap结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
//newValue = remappingFunction(key, oldValue); if newValue != null -> replace (key, oldValue) with (key, newValue)   
default V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
Objects.requireNonNull(remappingFunction);
V oldValue = get(key);
for(;;) {
V newValue = remappingFunction.apply(key, oldValue);
if (newValue == null) {
// delete mapping
if (oldValue != null || containsKey(key)) {
// something to remove
if (remove(key, oldValue)) {
// removed the old value as expected
return null;
}
// some other value replaced old value. try again.
oldValue = get(key);
} else {
// nothing to do. Leave things as they were.
return null;
}
} else {
// add or replace old mapping
if (oldValue != null) {
// replace
if (replace(key, oldValue, newValue)) {
// replaced as expected.
return newValue;
}
// some other value replaced old value. try again.
oldValue = get(key);
} else {
// add (replace if oldValue was null)
if ((oldValue = putIfAbsent(key, newValue)) == null) {
// replaced
return newValue;
}
// some other value replaced old value. try again.
}
}
}
}

some default methods here … …

ConcurrentHashMap

1
2
public class ConcurrentHashMap<K,V> extends AbstractMap<K,V>
implements ConcurrentMap<K,V>, Serializable{...}
  • All operations are thread-safe,retrieval operations do not entail locking, and there is not any support for locking the entire table in a way that prevents all access.

    This class is fully interoperable with Hashtable in programs that rely on its thread safety but not on its synchronization details.

    Retrievals reflect the results of the most recently completed update operations holding upon their onset.

    More formally, an update operation for a given key bears a happens-before relation with any (non-null) retrieval for that key reporting the updated value.

  • Bear in mind that the results of aggregate status methods including size, isEmpty, and containsValue are typically useful only when a map is not undergoing concurrent updates in other threads.
    Otherwise, the results of these methods reflect transient states that may be adequate for monitoring or estimation purposes, but not for program control.

  • scalable frequency map form of histogram or multiset) by using {@linkjava.util.concurrent.atomic.LongAdder} values and initializing via {@link #computeIfAbsent computeIfAbsent}.
    For example, to add a count to a {@code ConcurrentHashMap<String,LongAdder> freqs}, you can use {@code freqs.computeIfAbsent(k -> new LongAdder()).increment();}

  • Like Hashtable but unlike HashMap, this class does not allow null to be used as a key or value.


Methods:
forEach, search, reduce

Plain reductions: (There is not a form of this method for (key, value) function arguments since there is no corresponding return type.)
Mapped reductions: that accumulate the results of a given function applied to each element.
Reductions to scalar doubles, longs and ints , using a given basis value.


These bulk operations accept a {@code parallelismThreshold} argument.
这些批量操作接受@code parallelismThreshold参数。
Methods proceed sequentially if the current map size is estimated to be less than the given threshold.
如果当前映射大小估计小于给定阈值,则方法按顺序进行。
Using a value of {@code Long.MAX_VALUE} suppresses all parallelism.
使用@code long.max_value的值将禁止所有并行。

Using a value of {@code 1} results in maximal parallelism by partitioning into enough subtasks to fully utilize the {@link ForkJoinPool#commonPool()} that is used for all parallel computations.
使用{@代码1 }的值通过划分成足够多的子任务来最大化并行性,以便充分利用{ Link Link FokCuangPooSyPooPoCo()},用于所有并行计算。

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.
其他更新操作(插入、删除和替换)需要锁。
我们不想浪费将不同的锁对象与每个bin关联所需的空间,因此使用bin列表本身的第一个节点作为锁。


Code

ConcurrentHashMap

-------------再接再厉更进一步---------------