1 /*
2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3  *
4  * This code is free software; you can redistribute it and/or modify it
5  * under the terms of the GNU General Public License version 2 only, as
6  * published by the Free Software Foundation.  Oracle designates this
7  * particular file as subject to the "Classpath" exception as provided
8  * by Oracle in the LICENSE file that accompanied this code.
9  *
10  * This code is distributed in the hope that it will be useful, but WITHOUT
11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
13  * version 2 for more details (a copy is included in the LICENSE file that
14  * accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License version
17  * 2 along with this work; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
19  *
20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21  * or visit www.oracle.com if you need additional information or have any
22  * questions.
23  */

24
25 /*
26  * This file is available under and governed by the GNU General Public
27  * License version 2 only, as published by the Free Software Foundation.
28  * However, the following notice accompanied the original version of this
29  * file:
30  *
31  * Written by Doug Lea with assistance from members of JCP JSR-166
32  * Expert Group and released to the public domain, as explained at
33  * http://creativecommons.org/publicdomain/zero/1.0/
34  */

35
36 package java.util.concurrent.atomic;
37
38 import java.lang.invoke.VarHandle;
39 import java.util.function.LongBinaryOperator;
40 import java.util.function.LongUnaryOperator;
41
42 /**
43  * A {@code long} value that may be updated atomically.  See the
44  * {@link VarHandle} specification for descriptions of the properties
45  * of atomic accesses. An {@code AtomicLong} is used in applications
46  * such as atomically incremented sequence numbers, and cannot be used
47  * as a replacement for a {@link java.lang.Long}. However, this class
48  * does extend {@code Number} to allow uniform access by tools and
49  * utilities that deal with numerically-based classes.
50  *
51  * @since 1.5
52  * @author Doug Lea
53  */

54 public class AtomicLong extends Number implements java.io.Serializable {
55     private static final long serialVersionUID = 1927816293512124184L;
56
57     /**
58      * Records whether the underlying JVM supports lockless
59      * compareAndSet for longs. While the intrinsic compareAndSetLong
60      * method works in either case, some constructions should be
61      * handled at Java level to avoid locking user-visible locks.
62      */

63     static final boolean VM_SUPPORTS_LONG_CAS = VMSupportsCS8();
64
65     /**
66      * Returns whether underlying JVM supports lockless CompareAndSet
67      * for longs. Called only once and cached in VM_SUPPORTS_LONG_CAS.
68      */

69     private static native boolean VMSupportsCS8();
70
71     /*
72      * This class intended to be implemented using VarHandles, but there
73      * are unresolved cyclic startup dependencies.
74      */

75     private static final jdk.internal.misc.Unsafe U = jdk.internal.misc.Unsafe.getUnsafe();
76     private static final long VALUE = U.objectFieldOffset(AtomicLong.class"value");
77
78     private volatile long value;
79
80     /**
81      * Creates a new AtomicLong with the given initial value.
82      *
83      * @param initialValue the initial value
84      */

85     public AtomicLong(long initialValue) {
86         value = initialValue;
87     }
88
89     /**
90      * Creates a new AtomicLong with initial value {@code 0}.
91      */

92     public AtomicLong() {
93     }
94
95     /**
96      * Returns the current value,
97      * with memory effects as specified by {@link VarHandle#getVolatile}.
98      *
99      * @return the current value
100      */

101     public final long get() {
102         return value;
103     }
104
105     /**
106      * Sets the value to {@code newValue},
107      * with memory effects as specified by {@link VarHandle#setVolatile}.
108      *
109      * @param newValue the new value
110      */

111     public final void set(long newValue) {
112         // See JDK-8180620: Clarify VarHandle mixed-access subtleties
113         U.putLongVolatile(this, VALUE, newValue);
114     }
115
116     /**
117      * Sets the value to {@code newValue},
118      * with memory effects as specified by {@link VarHandle#setRelease}.
119      *
120      * @param newValue the new value
121      * @since 1.6
122      */

123     public final void lazySet(long newValue) {
124         U.putLongRelease(this, VALUE, newValue);
125     }
126
127     /**
128      * Atomically sets the value to {@code newValue} and returns the old value,
129      * with memory effects as specified by {@link VarHandle#getAndSet}.
130      *
131      * @param newValue the new value
132      * @return the previous value
133      */

134     public final long getAndSet(long newValue) {
135         return U.getAndSetLong(this, VALUE, newValue);
136     }
137
138     /**
139      * Atomically sets the value to {@code newValue}
140      * if the current value {@code == expectedValue},
141      * with memory effects as specified by {@link VarHandle#compareAndSet}.
142      *
143      * @param expectedValue the expected value
144      * @param newValue the new value
145      * @return {@code trueif successful. False return indicates that
146      * the actual value was not equal to the expected value.
147      */

148     public final boolean compareAndSet(long expectedValue, long newValue) {
149         return U.compareAndSetLong(this, VALUE, expectedValue, newValue);
150     }
151
152     /**
153      * Possibly atomically sets the value to {@code newValue}
154      * if the current value {@code == expectedValue},
155      * with memory effects as specified by {@link VarHandle#weakCompareAndSetPlain}.
156      *
157      * @deprecated This method has plain memory effects but the method
158      * name implies volatile memory effects (see methods such as
159      * {@link #compareAndExchange} and {@link #compareAndSet}).  To avoid
160      * confusion over plain or volatile memory effects it is recommended that
161      * the method {@link #weakCompareAndSetPlain} be used instead.
162      *
163      * @param expectedValue the expected value
164      * @param newValue the new value
165      * @return {@code trueif successful
166      * @see #weakCompareAndSetPlain
167      */

168     @Deprecated(since="9")
169     public final boolean weakCompareAndSet(long expectedValue, long newValue) {
170         return U.weakCompareAndSetLongPlain(this, VALUE, expectedValue, newValue);
171     }
172
173     /**
174      * Possibly atomically sets the value to {@code newValue}
175      * if the current value {@code == expectedValue},
176      * with memory effects as specified by {@link VarHandle#weakCompareAndSetPlain}.
177      *
178      * @param expectedValue the expected value
179      * @param newValue the new value
180      * @return {@code trueif successful
181      * @since 9
182      */

183     public final boolean weakCompareAndSetPlain(long expectedValue, long newValue) {
184         return U.weakCompareAndSetLongPlain(this, VALUE, expectedValue, newValue);
185     }
186
187     /**
188      * Atomically increments the current value,
189      * with memory effects as specified by {@link VarHandle#getAndAdd}.
190      *
191      * <p>Equivalent to {@code getAndAdd(1)}.
192      *
193      * @return the previous value
194      */

195     public final long getAndIncrement() {
196         return U.getAndAddLong(this, VALUE, 1L);
197     }
198
199     /**
200      * Atomically decrements the current value,
201      * with memory effects as specified by {@link VarHandle#getAndAdd}.
202      *
203      * <p>Equivalent to {@code getAndAdd(-1)}.
204      *
205      * @return the previous value
206      */

207     public final long getAndDecrement() {
208         return U.getAndAddLong(this, VALUE, -1L);
209     }
210
211     /**
212      * Atomically adds the given value to the current value,
213      * with memory effects as specified by {@link VarHandle#getAndAdd}.
214      *
215      * @param delta the value to add
216      * @return the previous value
217      */

218     public final long getAndAdd(long delta) {
219         return U.getAndAddLong(this, VALUE, delta);
220     }
221
222     /**
223      * Atomically increments the current value,
224      * with memory effects as specified by {@link VarHandle#getAndAdd}.
225      *
226      * <p>Equivalent to {@code addAndGet(1)}.
227      *
228      * @return the updated value
229      */

230     public final long incrementAndGet() {
231         return U.getAndAddLong(this, VALUE, 1L) + 1L;
232     }
233
234     /**
235      * Atomically decrements the current value,
236      * with memory effects as specified by {@link VarHandle#getAndAdd}.
237      *
238      * <p>Equivalent to {@code addAndGet(-1)}.
239      *
240      * @return the updated value
241      */

242     public final long decrementAndGet() {
243         return U.getAndAddLong(this, VALUE, -1L) - 1L;
244     }
245
246     /**
247      * Atomically adds the given value to the current value,
248      * with memory effects as specified by {@link VarHandle#getAndAdd}.
249      *
250      * @param delta the value to add
251      * @return the updated value
252      */

253     public final long addAndGet(long delta) {
254         return U.getAndAddLong(this, VALUE, delta) + delta;
255     }
256
257     /**
258      * Atomically updates (with memory effects as specified by {@link
259      * VarHandle#compareAndSet}) the current value with the results of
260      * applying the given function, returning the previous value. The
261      * function should be side-effect-free, since it may be re-applied
262      * when attempted updates fail due to contention among threads.
263      *
264      * @param updateFunction a side-effect-free function
265      * @return the previous value
266      * @since 1.8
267      */

268     public final long getAndUpdate(LongUnaryOperator updateFunction) {
269         long prev = get(), next = 0L;
270         for (boolean haveNext = false;;) {
271             if (!haveNext)
272                 next = updateFunction.applyAsLong(prev);
273             if (weakCompareAndSetVolatile(prev, next))
274                 return prev;
275             haveNext = (prev == (prev = get()));
276         }
277     }
278
279     /**
280      * Atomically updates (with memory effects as specified by {@link
281      * VarHandle#compareAndSet}) the current value with the results of
282      * applying the given function, returning the updated value. The
283      * function should be side-effect-free, since it may be re-applied
284      * when attempted updates fail due to contention among threads.
285      *
286      * @param updateFunction a side-effect-free function
287      * @return the updated value
288      * @since 1.8
289      */

290     public final long updateAndGet(LongUnaryOperator updateFunction) {
291         long prev = get(), next = 0L;
292         for (boolean haveNext = false;;) {
293             if (!haveNext)
294                 next = updateFunction.applyAsLong(prev);
295             if (weakCompareAndSetVolatile(prev, next))
296                 return next;
297             haveNext = (prev == (prev = get()));
298         }
299     }
300
301     /**
302      * Atomically updates (with memory effects as specified by {@link
303      * VarHandle#compareAndSet}) the current value with the results of
304      * applying the given function to the current and given values,
305      * returning the previous value. The function should be
306      * side-effect-free, since it may be re-applied when attempted
307      * updates fail due to contention among threads.  The function is
308      * applied with the current value as its first argument, and the
309      * given update as the second argument.
310      *
311      * @param x the update value
312      * @param accumulatorFunction a side-effect-free function of two arguments
313      * @return the previous value
314      * @since 1.8
315      */

316     public final long getAndAccumulate(long x,
317                                        LongBinaryOperator accumulatorFunction) {
318         long prev = get(), next = 0L;
319         for (boolean haveNext = false;;) {
320             if (!haveNext)
321                 next = accumulatorFunction.applyAsLong(prev, x);
322             if (weakCompareAndSetVolatile(prev, next))
323                 return prev;
324             haveNext = (prev == (prev = get()));
325         }
326     }
327
328     /**
329      * Atomically updates (with memory effects as specified by {@link
330      * VarHandle#compareAndSet}) the current value with the results of
331      * applying the given function to the current and given values,
332      * returning the updated value. The function should be
333      * side-effect-free, since it may be re-applied when attempted
334      * updates fail due to contention among threads.  The function is
335      * applied with the current value as its first argument, and the
336      * given update as the second argument.
337      *
338      * @param x the update value
339      * @param accumulatorFunction a side-effect-free function of two arguments
340      * @return the updated value
341      * @since 1.8
342      */

343     public final long accumulateAndGet(long x,
344                                        LongBinaryOperator accumulatorFunction) {
345         long prev = get(), next = 0L;
346         for (boolean haveNext = false;;) {
347             if (!haveNext)
348                 next = accumulatorFunction.applyAsLong(prev, x);
349             if (weakCompareAndSetVolatile(prev, next))
350                 return next;
351             haveNext = (prev == (prev = get()));
352         }
353     }
354
355     /**
356      * Returns the String representation of the current value.
357      * @return the String representation of the current value
358      */

359     public String toString() {
360         return Long.toString(get());
361     }
362
363     /**
364      * Returns the current value of this {@code AtomicLong} as an {@code int}
365      * after a narrowing primitive conversion,
366      * with memory effects as specified by {@link VarHandle#getVolatile}.
367      * @jls 5.1.3 Narrowing Primitive Conversions
368      */

369     public int intValue() {
370         return (int)get();
371     }
372
373     /**
374      * Returns the current value of this {@code AtomicLong} as a {@code long},
375      * with memory effects as specified by {@link VarHandle#getVolatile}.
376      * Equivalent to {@link #get()}.
377      */

378     public long longValue() {
379         return get();
380     }
381
382     /**
383      * Returns the current value of this {@code AtomicLong} as a {@code float}
384      * after a widening primitive conversion,
385      * with memory effects as specified by {@link VarHandle#getVolatile}.
386      * @jls 5.1.2 Widening Primitive Conversions
387      */

388     public float floatValue() {
389         return (float)get();
390     }
391
392     /**
393      * Returns the current value of this {@code AtomicLong} as a {@code double}
394      * after a widening primitive conversion,
395      * with memory effects as specified by {@link VarHandle#getVolatile}.
396      * @jls 5.1.2 Widening Primitive Conversions
397      */

398     public double doubleValue() {
399         return (double)get();
400     }
401
402     // jdk9
403
404     /**
405      * Returns the current value, with memory semantics of reading as if the
406      * variable was declared non-{@code volatile}.
407      *
408      * @return the value
409      * @since 9
410      */

411     public final long getPlain() {
412         return U.getLong(this, VALUE);
413     }
414
415     /**
416      * Sets the value to {@code newValue}, with memory semantics
417      * of setting as if the variable was declared non-{@code volatile}
418      * and non-{@code final}.
419      *
420      * @param newValue the new value
421      * @since 9
422      */

423     public final void setPlain(long newValue) {
424         U.putLong(this, VALUE, newValue);
425     }
426
427     /**
428      * Returns the current value,
429      * with memory effects as specified by {@link VarHandle#getOpaque}.
430      *
431      * @return the value
432      * @since 9
433      */

434     public final long getOpaque() {
435         return U.getLongOpaque(this, VALUE);
436     }
437
438     /**
439      * Sets the value to {@code newValue},
440      * with memory effects as specified by {@link VarHandle#setOpaque}.
441      *
442      * @param newValue the new value
443      * @since 9
444      */

445     public final void setOpaque(long newValue) {
446         U.putLongOpaque(this, VALUE, newValue);
447     }
448
449     /**
450      * Returns the current value,
451      * with memory effects as specified by {@link VarHandle#getAcquire}.
452      *
453      * @return the value
454      * @since 9
455      */

456     public final long getAcquire() {
457         return U.getLongAcquire(this, VALUE);
458     }
459
460     /**
461      * Sets the value to {@code newValue},
462      * with memory effects as specified by {@link VarHandle#setRelease}.
463      *
464      * @param newValue the new value
465      * @since 9
466      */

467     public final void setRelease(long newValue) {
468         U.putLongRelease(this, VALUE, newValue);
469     }
470
471     /**
472      * Atomically sets the value to {@code newValue} if the current value,
473      * referred to as the <em>witness value</em>, {@code == expectedValue},
474      * with memory effects as specified by
475      * {@link VarHandle#compareAndExchange}.
476      *
477      * @param expectedValue the expected value
478      * @param newValue the new value
479      * @return the witness value, which will be the same as the
480      * expected value if successful
481      * @since 9
482      */

483     public final long compareAndExchange(long expectedValue, long newValue) {
484         return U.compareAndExchangeLong(this, VALUE, expectedValue, newValue);
485     }
486
487     /**
488      * Atomically sets the value to {@code newValue} if the current value,
489      * referred to as the <em>witness value</em>, {@code == expectedValue},
490      * with memory effects as specified by
491      * {@link VarHandle#compareAndExchangeAcquire}.
492      *
493      * @param expectedValue the expected value
494      * @param newValue the new value
495      * @return the witness value, which will be the same as the
496      * expected value if successful
497      * @since 9
498      */

499     public final long compareAndExchangeAcquire(long expectedValue, long newValue) {
500         return U.compareAndExchangeLongAcquire(this, VALUE, expectedValue, newValue);
501     }
502
503     /**
504      * Atomically sets the value to {@code newValue} if the current value,
505      * referred to as the <em>witness value</em>, {@code == expectedValue},
506      * with memory effects as specified by
507      * {@link VarHandle#compareAndExchangeRelease}.
508      *
509      * @param expectedValue the expected value
510      * @param newValue the new value
511      * @return the witness value, which will be the same as the
512      * expected value if successful
513      * @since 9
514      */

515     public final long compareAndExchangeRelease(long expectedValue, long newValue) {
516         return U.compareAndExchangeLongRelease(this, VALUE, expectedValue, newValue);
517     }
518
519     /**
520      * Possibly atomically sets the value to {@code newValue}
521      * if the current value {@code == expectedValue},
522      * with memory effects as specified by
523      * {@link VarHandle#weakCompareAndSet}.
524      *
525      * @param expectedValue the expected value
526      * @param newValue the new value
527      * @return {@code trueif successful
528      * @since 9
529      */

530     public final boolean weakCompareAndSetVolatile(long expectedValue, long newValue) {
531         return U.weakCompareAndSetLong(this, VALUE, expectedValue, newValue);
532     }
533
534     /**
535      * Possibly atomically sets the value to {@code newValue}
536      * if the current value {@code == expectedValue},
537      * with memory effects as specified by
538      * {@link VarHandle#weakCompareAndSetAcquire}.
539      *
540      * @param expectedValue the expected value
541      * @param newValue the new value
542      * @return {@code trueif successful
543      * @since 9
544      */

545     public final boolean weakCompareAndSetAcquire(long expectedValue, long newValue) {
546         return U.weakCompareAndSetLongAcquire(this, VALUE, expectedValue, newValue);
547     }
548
549     /**
550      * Possibly atomically sets the value to {@code newValue}
551      * if the current value {@code == expectedValue},
552      * with memory effects as specified by
553      * {@link VarHandle#weakCompareAndSetRelease}.
554      *
555      * @param expectedValue the expected value
556      * @param newValue the new value
557      * @return {@code trueif successful
558      * @since 9
559      */

560     public final boolean weakCompareAndSetRelease(long expectedValue, long newValue) {
561         return U.weakCompareAndSetLongRelease(this, VALUE, expectedValue, newValue);
562     }
563
564 }
565