ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jdk8/java/util/concurrent/atomic/LongAccumulator.java
Revision: 1.3
Committed: Thu Sep 15 06:57:06 2016 UTC (7 years, 8 months ago) by jsr166
Branch: MAIN
CVS Tags: HEAD
Changes since 1.2: +9 -7 lines
Log Message:
improve readability; fix errorprone warning OperatorPrecedence

File Contents

# Content
1 /*
2 * Written by Doug Lea with assistance from members of JCP JSR-166
3 * Expert Group and released to the public domain, as explained at
4 * http://creativecommons.org/publicdomain/zero/1.0/
5 */
6
7 package java.util.concurrent.atomic;
8
9 import java.io.Serializable;
10 import java.util.function.LongBinaryOperator;
11
12 /**
13 * One or more variables that together maintain a running {@code long}
14 * value updated using a supplied function. When updates (method
15 * {@link #accumulate}) are contended across threads, the set of variables
16 * may grow dynamically to reduce contention. Method {@link #get}
17 * (or, equivalently, {@link #longValue}) returns the current value
18 * across the variables maintaining updates.
19 *
20 * <p>This class is usually preferable to {@link AtomicLong} when
21 * multiple threads update a common value that is used for purposes such
22 * as collecting statistics, not for fine-grained synchronization
23 * control. Under low update contention, the two classes have similar
24 * characteristics. But under high contention, expected throughput of
25 * this class is significantly higher, at the expense of higher space
26 * consumption.
27 *
28 * <p>The order of accumulation within or across threads is not
29 * guaranteed and cannot be depended upon, so this class is only
30 * applicable to functions for which the order of accumulation does
31 * not matter. The supplied accumulator function should be
32 * side-effect-free, since it may be re-applied when attempted updates
33 * fail due to contention among threads. The function is applied with
34 * the current value as its first argument, and the given update as
35 * the second argument. For example, to maintain a running maximum
36 * value, you could supply {@code Long::max} along with {@code
37 * Long.MIN_VALUE} as the identity.
38 *
39 * <p>Class {@link LongAdder} provides analogs of the functionality of
40 * this class for the common special case of maintaining counts and
41 * sums. The call {@code new LongAdder()} is equivalent to {@code new
42 * LongAccumulator((x, y) -> x + y, 0L)}.
43 *
44 * <p>This class extends {@link Number}, but does <em>not</em> define
45 * methods such as {@code equals}, {@code hashCode} and {@code
46 * compareTo} because instances are expected to be mutated, and so are
47 * not useful as collection keys.
48 *
49 * @since 1.8
50 * @author Doug Lea
51 */
52 public class LongAccumulator extends Striped64 implements Serializable {
53 private static final long serialVersionUID = 7249069246863182397L;
54
55 private final LongBinaryOperator function;
56 private final long identity;
57
58 /**
59 * Creates a new instance using the given accumulator function
60 * and identity element.
61 * @param accumulatorFunction a side-effect-free function of two arguments
62 * @param identity identity (initial value) for the accumulator function
63 */
64 public LongAccumulator(LongBinaryOperator accumulatorFunction,
65 long identity) {
66 this.function = accumulatorFunction;
67 base = this.identity = identity;
68 }
69
70 /**
71 * Updates with the given value.
72 *
73 * @param x the value
74 */
75 public void accumulate(long x) {
76 Cell[] as; long b, v, r; int m; Cell a;
77 if ((as = cells) != null
78 || ((r = function.applyAsLong(b = base, x)) != b
79 && !casBase(b, r))) {
80 boolean uncontended = true;
81 if (as == null
82 || (m = as.length - 1) < 0
83 || (a = as[getProbe() & m]) == null
84 || !(uncontended =
85 (r = function.applyAsLong(v = a.value, x)) == v
86 || a.cas(v, r)))
87 longAccumulate(x, function, uncontended);
88 }
89 }
90
91 /**
92 * Returns the current value. The returned value is <em>NOT</em>
93 * an atomic snapshot; invocation in the absence of concurrent
94 * updates returns an accurate result, but concurrent updates that
95 * occur while the value is being calculated might not be
96 * incorporated.
97 *
98 * @return the current value
99 */
100 public long get() {
101 Cell[] as = cells;
102 long result = base;
103 if (as != null) {
104 for (Cell a : as)
105 if (a != null)
106 result = function.applyAsLong(result, a.value);
107 }
108 return result;
109 }
110
111 /**
112 * Resets variables maintaining updates to the identity value.
113 * This method may be a useful alternative to creating a new
114 * updater, but is only effective if there are no concurrent
115 * updates. Because this method is intrinsically racy, it should
116 * only be used when it is known that no threads are concurrently
117 * updating.
118 */
119 public void reset() {
120 Cell[] as = cells;
121 base = identity;
122 if (as != null) {
123 for (Cell a : as)
124 if (a != null)
125 a.reset(identity);
126 }
127 }
128
129 /**
130 * Equivalent in effect to {@link #get} followed by {@link
131 * #reset}. This method may apply for example during quiescent
132 * points between multithreaded computations. If there are
133 * updates concurrent with this method, the returned value is
134 * <em>not</em> guaranteed to be the final value occurring before
135 * the reset.
136 *
137 * @return the value before reset
138 */
139 public long getThenReset() {
140 Cell[] as = cells;
141 long result = base;
142 base = identity;
143 if (as != null) {
144 for (Cell a : as) {
145 if (a != null) {
146 long v = a.value;
147 a.reset(identity);
148 result = function.applyAsLong(result, v);
149 }
150 }
151 }
152 return result;
153 }
154
155 /**
156 * Returns the String representation of the current value.
157 * @return the String representation of the current value
158 */
159 public String toString() {
160 return Long.toString(get());
161 }
162
163 /**
164 * Equivalent to {@link #get}.
165 *
166 * @return the current value
167 */
168 public long longValue() {
169 return get();
170 }
171
172 /**
173 * Returns the {@linkplain #get current value} as an {@code int}
174 * after a narrowing primitive conversion.
175 */
176 public int intValue() {
177 return (int)get();
178 }
179
180 /**
181 * Returns the {@linkplain #get current value} as a {@code float}
182 * after a widening primitive conversion.
183 */
184 public float floatValue() {
185 return (float)get();
186 }
187
188 /**
189 * Returns the {@linkplain #get current value} as a {@code double}
190 * after a widening primitive conversion.
191 */
192 public double doubleValue() {
193 return (double)get();
194 }
195
196 /**
197 * Serialization proxy, used to avoid reference to the non-public
198 * Striped64 superclass in serialized forms.
199 * @serial include
200 */
201 private static class SerializationProxy implements Serializable {
202 private static final long serialVersionUID = 7249069246863182397L;
203
204 /**
205 * The current value returned by get().
206 * @serial
207 */
208 private final long value;
209
210 /**
211 * The function used for updates.
212 * @serial
213 */
214 private final LongBinaryOperator function;
215
216 /**
217 * The identity value.
218 * @serial
219 */
220 private final long identity;
221
222 SerializationProxy(long value,
223 LongBinaryOperator function,
224 long identity) {
225 this.value = value;
226 this.function = function;
227 this.identity = identity;
228 }
229
230 /**
231 * Returns a {@code LongAccumulator} object with initial state
232 * held by this proxy.
233 *
234 * @return a {@code LongAccumulator} object with initial state
235 * held by this proxy
236 */
237 private Object readResolve() {
238 LongAccumulator a = new LongAccumulator(function, identity);
239 a.base = value;
240 return a;
241 }
242 }
243
244 /**
245 * Returns a
246 * <a href="../../../../serialized-form.html#java.util.concurrent.atomic.LongAccumulator.SerializationProxy">
247 * SerializationProxy</a>
248 * representing the state of this instance.
249 *
250 * @return a {@link SerializationProxy}
251 * representing the state of this instance
252 */
253 private Object writeReplace() {
254 return new SerializationProxy(get(), function, identity);
255 }
256
257 /**
258 * @param s the stream
259 * @throws java.io.InvalidObjectException always
260 */
261 private void readObject(java.io.ObjectInputStream s)
262 throws java.io.InvalidObjectException {
263 throw new java.io.InvalidObjectException("Proxy required");
264 }
265
266 }