4 |
|
* http://creativecommons.org/publicdomain/zero/1.0/ |
5 |
|
*/ |
6 |
|
|
7 |
< |
package jsr166e.extra; |
7 |
> |
package jsr166e; |
8 |
|
import jsr166e.LongAdder; |
9 |
– |
import java.util.concurrent.ConcurrentHashMap; |
9 |
|
import java.util.Map; |
10 |
|
import java.util.Set; |
11 |
|
import java.io.Serializable; |
20 |
|
* <p><em>jsr166e note: This class is targeted to be placed in |
21 |
|
* java.util.concurrent.atomic<em> |
22 |
|
* |
23 |
+ |
* @since 1.8 |
24 |
|
* @author Doug Lea |
25 |
|
*/ |
26 |
|
public class LongAdderTable<K> implements Serializable { |
27 |
|
/** Relies on default serialization */ |
28 |
|
private static final long serialVersionUID = 7249369246863182397L; |
29 |
|
|
30 |
– |
/** Concurrency parameter for map -- we assume high contention */ |
31 |
– |
private static final int MAP_SEGMENTS = |
32 |
– |
Math.max(16, Runtime.getRuntime().availableProcessors()); |
33 |
– |
|
30 |
|
/** The underlying map */ |
31 |
< |
private final ConcurrentHashMap<K, LongAdder> map; |
31 |
> |
private final ConcurrentHashMapV8<K, LongAdder> map; |
32 |
> |
|
33 |
> |
static final class CreateAdder |
34 |
> |
implements ConcurrentHashMapV8.MappingFunction<Object, LongAdder> { |
35 |
> |
public LongAdder map(Object unused) { return new LongAdder(); } |
36 |
> |
} |
37 |
> |
|
38 |
> |
private static final CreateAdder createAdder = new CreateAdder(); |
39 |
|
|
40 |
|
/** |
41 |
|
* Creates a new empty table. |
42 |
|
*/ |
43 |
|
public LongAdderTable() { |
44 |
< |
map = new ConcurrentHashMap<K, LongAdder>(16, 0.75f, MAP_SEGMENTS); |
44 |
> |
map = new ConcurrentHashMapV8<K, LongAdder>(); |
45 |
|
} |
46 |
|
|
47 |
|
/** |
72 |
|
*/ |
73 |
|
public void add(K key, long x) { |
74 |
|
LongAdder a = map.get(key); |
75 |
< |
if (a == null) { |
76 |
< |
LongAdder r = new LongAdder(); |
74 |
< |
if ((a = map.putIfAbsent(key, r)) == null) |
75 |
< |
a = r; |
76 |
< |
} |
75 |
> |
if (a == null) |
76 |
> |
a = map.computeIfAbsent(key, createAdder); |
77 |
|
a.add(x); |
78 |
|
} |
79 |
|
|
136 |
|
/** |
137 |
|
* Returns the sum totalled across all keys. |
138 |
|
* |
139 |
< |
* @return the sum totalled across all keys. |
139 |
> |
* @return the sum totalled across all keys |
140 |
|
*/ |
141 |
|
public long sumAll() { |
142 |
|
long sum = 0L; |
156 |
|
/** |
157 |
|
* Totals, then resets, the sums associated with all keys. |
158 |
|
* |
159 |
< |
* @return the sum totalled across all keys. |
159 |
> |
* @return the sum totalled across all keys |
160 |
|
*/ |
161 |
|
public long sumThenResetAll() { |
162 |
|
long sum = 0L; |