19 |
|
* #longValue}) returns the current total combined across the |
20 |
|
* variables maintaining the sum. |
21 |
|
* |
22 |
< |
* <p> This class is usually preferable to {@link AtomicLong} when |
22 |
> |
* <p>This class is usually preferable to {@link AtomicLong} when |
23 |
|
* multiple threads update a common sum that is used for purposes such |
24 |
|
* as collecting statistics, not for fine-grained synchronization |
25 |
|
* control. Under low update contention, the two classes have similar |
28 |
|
* consumption. |
29 |
|
* |
30 |
|
* <p>This class extends {@link Number}, but does <em>not</em> define |
31 |
< |
* methods such as {@code hashCode} and {@code compareTo} because |
32 |
< |
* instances are expected to be mutated, and so are not useful as |
33 |
< |
* collection keys. |
31 |
> |
* methods such as {@code equals}, {@code hashCode} and {@code |
32 |
> |
* compareTo} because instances are expected to be mutated, and so are |
33 |
> |
* not useful as collection keys. |
34 |
|
* |
35 |
|
* <p><em>jsr166e note: This class is targeted to be placed in |
36 |
< |
* java.util.concurrent.atomic<em> |
36 |
> |
* java.util.concurrent.atomic.</em> |
37 |
|
* |
38 |
+ |
* @since 1.8 |
39 |
|
* @author Doug Lea |
40 |
|
*/ |
41 |
|
public class LongAdder extends Striped64 implements Serializable { |
85 |
|
|
86 |
|
/** |
87 |
|
* Returns the current sum. The returned value is <em>NOT</em> an |
88 |
< |
* atomic snapshot: Invocation in the absence of concurrent |
88 |
> |
* atomic snapshot: invocation in the absence of concurrent |
89 |
|
* updates returns an accurate result, but concurrent updates that |
90 |
|
* occur while the sum is being calculated might not be |
91 |
|
* incorporated. |
93 |
|
* @return the sum |
94 |
|
*/ |
95 |
|
public long sum() { |
95 |
– |
Cell[] as = cells; |
96 |
|
long sum = base; |
97 |
+ |
Cell[] as = cells; |
98 |
|
if (as != null) { |
99 |
|
int n = as.length; |
100 |
|
for (int i = 0; i < n; ++i) { |
128 |
|
* @return the sum |
129 |
|
*/ |
130 |
|
public long sumThenReset() { |
130 |
– |
Cell[] as = cells; |
131 |
|
long sum = base; |
132 |
+ |
Cell[] as = cells; |
133 |
|
base = 0L; |
134 |
|
if (as != null) { |
135 |
|
int n = as.length; |
136 |
|
for (int i = 0; i < n; ++i) { |
137 |
|
Cell a = as[i]; |
138 |
|
if (a != null) { |
139 |
< |
long v = a.value; |
139 |
> |
sum += a.value; |
140 |
|
a.value = 0L; |
140 |
– |
sum += v; |
141 |
|
} |
142 |
|
} |
143 |
|
} |
146 |
|
|
147 |
|
/** |
148 |
|
* Returns the String representation of the {@link #sum}. |
149 |
< |
* @return the String representation of the {@link #sum}. |
149 |
> |
* @return the String representation of the {@link #sum} |
150 |
|
*/ |
151 |
|
public String toString() { |
152 |
|
return Long.toString(sum()); |