• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.MethodHandles;
39 import java.lang.invoke.VarHandle;
40 import java.util.function.IntBinaryOperator;
41 import java.util.function.IntUnaryOperator;
42 
43 /**
44  * An {@code int} value that may be updated atomically.  See the
45  * {@link VarHandle} specification for descriptions of the properties
46  * of atomic accesses. An {@code AtomicInteger} is used in
47  * applications such as atomically incremented counters, and cannot be
48  * used as a replacement for an {@link java.lang.Integer}. However,
49  * this class does extend {@code Number} to allow uniform access by
50  * tools and utilities that deal with numerically-based classes.
51  *
52  * @since 1.5
53  * @author Doug Lea
54  */
55 public class AtomicInteger extends Number implements java.io.Serializable {
56     private static final long serialVersionUID = 6214790243416807050L;
57 
58     /*
59      * This class intended to be implemented using VarHandles, but there
60      * are unresolved cyclic startup dependencies.
61      */
62     // BEGIN Android-changed: Using VarHandle instead of Unsafe
63     // private static final jdk.internal.misc.Unsafe U = jdk.internal.misc.Unsafe.getUnsafe();
64     // private static final long VALUE = U.objectFieldOffset(AtomicInteger.class, "value");
65     private static final VarHandle VALUE;
66     static {
67         try {
68             MethodHandles.Lookup l = MethodHandles.lookup();
69             VALUE = l.findVarHandle(AtomicInteger.class, "value", int.class);
70         } catch (ReflectiveOperationException e) {
71             throw new ExceptionInInitializerError(e);
72         }
73     }
74     // END Android-changed: Using VarHandle instead of Unsafe
75 
76     private volatile int value;
77 
78     /**
79      * Creates a new AtomicInteger with the given initial value.
80      *
81      * @param initialValue the initial value
82      */
AtomicInteger(int initialValue)83     public AtomicInteger(int initialValue) {
84         value = initialValue;
85     }
86 
87     /**
88      * Creates a new AtomicInteger with initial value {@code 0}.
89      */
AtomicInteger()90     public AtomicInteger() {
91     }
92 
93     /**
94      * Returns the current value,
95      * with memory effects as specified by {@link VarHandle#getVolatile}.
96      *
97      * @return the current value
98      */
get()99     public final int get() {
100         return value;
101     }
102 
103     /**
104      * Sets the value to {@code newValue},
105      * with memory effects as specified by {@link VarHandle#setVolatile}.
106      *
107      * @param newValue the new value
108      */
set(int newValue)109     public final void set(int newValue) {
110         value = newValue;
111     }
112 
113     /**
114      * Sets the value to {@code newValue},
115      * with memory effects as specified by {@link VarHandle#setRelease}.
116      *
117      * @param newValue the new value
118      * @since 1.6
119      */
lazySet(int newValue)120     public final void lazySet(int newValue) {
121         // Android-changed: Using VarHandle instead of Unsafe
122         // U.putIntRelease(this, VALUE, newValue);
123         VALUE.setRelease(this, newValue);
124     }
125 
126     /**
127      * Atomically sets the value to {@code newValue} and returns the old value,
128      * with memory effects as specified by {@link VarHandle#getAndSet}.
129      *
130      * @param newValue the new value
131      * @return the previous value
132      */
getAndSet(int newValue)133     public final int getAndSet(int newValue) {
134         // Android-changed: Using VarHandle instead of Unsafe
135         // return U.getAndSetInt(this, VALUE, newValue);
136         return (int)VALUE.getAndSet(this, newValue);
137     }
138 
139     /**
140      * Atomically sets the value to {@code newValue}
141      * if the current value {@code == expectedValue},
142      * with memory effects as specified by {@link VarHandle#compareAndSet}.
143      *
144      * @param expectedValue the expected value
145      * @param newValue the new value
146      * @return {@code true} if successful. False return indicates that
147      * the actual value was not equal to the expected value.
148      */
compareAndSet(int expectedValue, int newValue)149     public final boolean compareAndSet(int expectedValue, int newValue) {
150         // Android-changed: Using VarHandle instead of Unsafe
151         // return U.compareAndSetInt(this, VALUE, expectedValue, newValue);
152         return VALUE.compareAndSet(this, expectedValue, newValue);
153     }
154 
155     /**
156      * Possibly atomically sets the value to {@code newValue}
157      * if the current value {@code == expectedValue},
158      * with memory effects as specified by {@link VarHandle#weakCompareAndSetPlain}.
159      *
160      * @deprecated This method has plain memory effects but the method
161      * name implies volatile memory effects (see methods such as
162      * {@link #compareAndExchange} and {@link #compareAndSet}).  To avoid
163      * confusion over plain or volatile memory effects it is recommended that
164      * the method {@link #weakCompareAndSetPlain} be used instead.
165      *
166      * @param expectedValue the expected value
167      * @param newValue the new value
168      * @return {@code true} if successful
169      * @see #weakCompareAndSetPlain
170      */
171     @Deprecated(since="9")
weakCompareAndSet(int expectedValue, int newValue)172     public final boolean weakCompareAndSet(int expectedValue, int newValue) {
173         // Android-changed: Using VarHandle instead of Unsafe
174         // return U.weakCompareAndSetIntPlain(this, VALUE, expectedValue, newValue);
175         return VALUE.weakCompareAndSetPlain(this, expectedValue, newValue);
176     }
177 
178     /**
179      * Possibly atomically sets the value to {@code newValue}
180      * if the current value {@code == expectedValue},
181      * with memory effects as specified by {@link VarHandle#weakCompareAndSetPlain}.
182      *
183      * @param expectedValue the expected value
184      * @param newValue the new value
185      * @return {@code true} if successful
186      * @since 9
187      */
weakCompareAndSetPlain(int expectedValue, int newValue)188     public final boolean weakCompareAndSetPlain(int expectedValue, int newValue) {
189         // Android-changed: Using VarHandle instead of Unsafe
190         // return U.weakCompareAndSetIntPlain(this, VALUE, expectedValue, newValue);
191         return VALUE.weakCompareAndSetPlain(this, expectedValue, newValue);
192     }
193 
194     /**
195      * Atomically increments the current value,
196      * with memory effects as specified by {@link VarHandle#getAndAdd}.
197      *
198      * <p>Equivalent to {@code getAndAdd(1)}.
199      *
200      * @return the previous value
201      */
getAndIncrement()202     public final int getAndIncrement() {
203         // Android-changed: Using VarHandle instead of Unsafe
204         // return U.getAndAddInt(this, VALUE, 1);
205         return (int)VALUE.getAndAdd(this, 1);
206     }
207 
208     /**
209      * Atomically decrements the current value,
210      * with memory effects as specified by {@link VarHandle#getAndAdd}.
211      *
212      * <p>Equivalent to {@code getAndAdd(-1)}.
213      *
214      * @return the previous value
215      */
getAndDecrement()216     public final int getAndDecrement() {
217         // Android-changed: Using VarHandle instead of Unsafe
218         // return U.getAndAddInt(this, VALUE, -1);
219         return (int)VALUE.getAndAdd(this, -1);
220     }
221 
222     /**
223      * Atomically adds the given value to the current value,
224      * with memory effects as specified by {@link VarHandle#getAndAdd}.
225      *
226      * @param delta the value to add
227      * @return the previous value
228      */
getAndAdd(int delta)229     public final int getAndAdd(int delta) {
230         // Android-changed: Using VarHandle instead of Unsafe
231         // return U.getAndAddInt(this, VALUE, delta);
232         return (int)VALUE.getAndAdd(this, delta);
233     }
234 
235     /**
236      * Atomically increments the current value,
237      * with memory effects as specified by {@link VarHandle#getAndAdd}.
238      *
239      * <p>Equivalent to {@code addAndGet(1)}.
240      *
241      * @return the updated value
242      */
incrementAndGet()243     public final int incrementAndGet() {
244         // Android-changed: Using VarHandle instead of Unsafe
245         // return U.getAndAddInt(this, VALUE, 1) + 1;
246         return (int)VALUE.getAndAdd(this, 1) + 1;
247     }
248 
249     /**
250      * Atomically decrements the current value,
251      * with memory effects as specified by {@link VarHandle#getAndAdd}.
252      *
253      * <p>Equivalent to {@code addAndGet(-1)}.
254      *
255      * @return the updated value
256      */
decrementAndGet()257     public final int decrementAndGet() {
258         // Android-changed: Using VarHandle instead of Unsafe
259         // return U.getAndAddInt(this, VALUE, -1) - 1;
260         return (int)VALUE.getAndAdd(this, -1) - 1;
261     }
262 
263     /**
264      * Atomically adds the given value to the current value,
265      * with memory effects as specified by {@link VarHandle#getAndAdd}.
266      *
267      * @param delta the value to add
268      * @return the updated value
269      */
addAndGet(int delta)270     public final int addAndGet(int delta) {
271         // Android-changed: Using VarHandle instead of Unsafe
272         // return U.getAndAddInt(this, VALUE, delta) + delta;
273         return (int)VALUE.getAndAdd(this, delta) + delta;
274     }
275 
276     /**
277      * Atomically updates (with memory effects as specified by {@link
278      * VarHandle#compareAndSet}) the current value with the results of
279      * applying the given function, returning the previous value. The
280      * function should be side-effect-free, since it may be re-applied
281      * when attempted updates fail due to contention among threads.
282      *
283      * @param updateFunction a side-effect-free function
284      * @return the previous value
285      * @since 1.8
286      */
getAndUpdate(IntUnaryOperator updateFunction)287     public final int getAndUpdate(IntUnaryOperator updateFunction) {
288         int prev = get(), next = 0;
289         for (boolean haveNext = false;;) {
290             if (!haveNext)
291                 next = updateFunction.applyAsInt(prev);
292             if (weakCompareAndSetVolatile(prev, next))
293                 return prev;
294             haveNext = (prev == (prev = get()));
295         }
296     }
297 
298     /**
299      * Atomically updates (with memory effects as specified by {@link
300      * VarHandle#compareAndSet}) the current value with the results of
301      * applying the given function, returning the updated value. The
302      * function should be side-effect-free, since it may be re-applied
303      * when attempted updates fail due to contention among threads.
304      *
305      * @param updateFunction a side-effect-free function
306      * @return the updated value
307      * @since 1.8
308      */
updateAndGet(IntUnaryOperator updateFunction)309     public final int updateAndGet(IntUnaryOperator updateFunction) {
310         int prev = get(), next = 0;
311         for (boolean haveNext = false;;) {
312             if (!haveNext)
313                 next = updateFunction.applyAsInt(prev);
314             if (weakCompareAndSetVolatile(prev, next))
315                 return next;
316             haveNext = (prev == (prev = get()));
317         }
318     }
319 
320     /**
321      * Atomically updates (with memory effects as specified by {@link
322      * VarHandle#compareAndSet}) the current value with the results of
323      * applying the given function to the current and given values,
324      * returning the previous value. The function should be
325      * side-effect-free, since it may be re-applied when attempted
326      * updates fail due to contention among threads.  The function is
327      * applied with the current value as its first argument, and the
328      * given update as the second argument.
329      *
330      * @param x the update value
331      * @param accumulatorFunction a side-effect-free function of two arguments
332      * @return the previous value
333      * @since 1.8
334      */
getAndAccumulate(int x, IntBinaryOperator accumulatorFunction)335     public final int getAndAccumulate(int x,
336                                       IntBinaryOperator accumulatorFunction) {
337         int prev = get(), next = 0;
338         for (boolean haveNext = false;;) {
339             if (!haveNext)
340                 next = accumulatorFunction.applyAsInt(prev, x);
341             if (weakCompareAndSetVolatile(prev, next))
342                 return prev;
343             haveNext = (prev == (prev = get()));
344         }
345     }
346 
347     /**
348      * Atomically updates (with memory effects as specified by {@link
349      * VarHandle#compareAndSet}) the current value with the results of
350      * applying the given function to the current and given values,
351      * returning the updated value. The function should be
352      * side-effect-free, since it may be re-applied when attempted
353      * updates fail due to contention among threads.  The function is
354      * applied with the current value as its first argument, and the
355      * given update as the second argument.
356      *
357      * @param x the update value
358      * @param accumulatorFunction a side-effect-free function of two arguments
359      * @return the updated value
360      * @since 1.8
361      */
accumulateAndGet(int x, IntBinaryOperator accumulatorFunction)362     public final int accumulateAndGet(int x,
363                                       IntBinaryOperator accumulatorFunction) {
364         int prev = get(), next = 0;
365         for (boolean haveNext = false;;) {
366             if (!haveNext)
367                 next = accumulatorFunction.applyAsInt(prev, x);
368             if (weakCompareAndSetVolatile(prev, next))
369                 return next;
370             haveNext = (prev == (prev = get()));
371         }
372     }
373 
374     /**
375      * Returns the String representation of the current value.
376      * @return the String representation of the current value
377      */
toString()378     public String toString() {
379         return Integer.toString(get());
380     }
381 
382     /**
383      * Returns the current value of this {@code AtomicInteger} as an
384      * {@code int},
385      * with memory effects as specified by {@link VarHandle#getVolatile}.
386      *
387      * Equivalent to {@link #get()}.
388      */
intValue()389     public int intValue() {
390         return get();
391     }
392 
393     /**
394      * Returns the current value of this {@code AtomicInteger} as a
395      * {@code long} after a widening primitive conversion,
396      * with memory effects as specified by {@link VarHandle#getVolatile}.
397      * @jls 5.1.2 Widening Primitive Conversions
398      */
longValue()399     public long longValue() {
400         return (long)get();
401     }
402 
403     /**
404      * Returns the current value of this {@code AtomicInteger} as a
405      * {@code float} after a widening primitive conversion,
406      * with memory effects as specified by {@link VarHandle#getVolatile}.
407      * @jls 5.1.2 Widening Primitive Conversions
408      */
floatValue()409     public float floatValue() {
410         return (float)get();
411     }
412 
413     /**
414      * Returns the current value of this {@code AtomicInteger} as a
415      * {@code double} after a widening primitive conversion,
416      * with memory effects as specified by {@link VarHandle#getVolatile}.
417      * @jls 5.1.2 Widening Primitive Conversions
418      */
doubleValue()419     public double doubleValue() {
420         return (double)get();
421     }
422 
423     // jdk9
424 
425     /**
426      * Returns the current value, with memory semantics of reading as
427      * if the variable was declared non-{@code volatile}.
428      *
429      * @return the value
430      * @since 9
431      */
getPlain()432     public final int getPlain() {
433         // Android-changed: Using VarHandle instead of Unsafe
434         // return U.getInt(this, VALUE);
435         return (int)VALUE.get(this);
436     }
437 
438     /**
439      * Sets the value to {@code newValue}, with memory semantics
440      * of setting as if the variable was declared non-{@code volatile}
441      * and non-{@code final}.
442      *
443      * @param newValue the new value
444      * @since 9
445      */
setPlain(int newValue)446     public final void setPlain(int newValue) {
447         // Android-changed: Using VarHandle instead of Unsafe
448         // U.putInt(this, VALUE, newValue);
449         VALUE.set(this, newValue);
450     }
451 
452     /**
453      * Returns the current value,
454      * with memory effects as specified by {@link VarHandle#getOpaque}.
455      *
456      * @return the value
457      * @since 9
458      */
getOpaque()459     public final int getOpaque() {
460         // Android-changed: Using VarHandle instead of Unsafe
461         // return U.getIntOpaque(this, VALUE);
462         return (int)VALUE.getOpaque(this);
463     }
464 
465     /**
466      * Sets the value to {@code newValue},
467      * with memory effects as specified by {@link VarHandle#setOpaque}.
468      *
469      * @param newValue the new value
470      * @since 9
471      */
setOpaque(int newValue)472     public final void setOpaque(int newValue) {
473         // Android-changed: Using VarHandle instead of Unsafe
474         // U.putIntOpaque(this, VALUE, newValue);
475         VALUE.setOpaque(this, newValue);
476     }
477 
478     /**
479      * Returns the current value,
480      * with memory effects as specified by {@link VarHandle#getAcquire}.
481      *
482      * @return the value
483      * @since 9
484      */
getAcquire()485     public final int getAcquire() {
486         // Android-changed: Using VarHandle instead of Unsafe
487         // return U.getIntAcquire(this, VALUE);
488         return (int)VALUE.getAcquire(this);
489     }
490 
491     /**
492      * Sets the value to {@code newValue},
493      * with memory effects as specified by {@link VarHandle#setRelease}.
494      *
495      * @param newValue the new value
496      * @since 9
497      */
setRelease(int newValue)498     public final void setRelease(int newValue) {
499         // Android-changed: Using VarHandle instead of Unsafe
500         // U.putIntRelease(this, VALUE, newValue);
501         VALUE.setRelease(this, newValue);
502     }
503 
504     /**
505      * Atomically sets the value to {@code newValue} if the current value,
506      * referred to as the <em>witness value</em>, {@code == expectedValue},
507      * with memory effects as specified by
508      * {@link VarHandle#compareAndExchange}.
509      *
510      * @param expectedValue the expected value
511      * @param newValue the new value
512      * @return the witness value, which will be the same as the
513      * expected value if successful
514      * @since 9
515      */
compareAndExchange(int expectedValue, int newValue)516     public final int compareAndExchange(int expectedValue, int newValue) {
517         // Android-changed: Using VarHandle instead of Unsafe
518         // return U.compareAndExchangeInt(this, VALUE, expectedValue, newValue);
519         return (int)VALUE.compareAndExchange(this, expectedValue, newValue);
520     }
521 
522     /**
523      * Atomically sets the value to {@code newValue} if the current value,
524      * referred to as the <em>witness value</em>, {@code == expectedValue},
525      * with memory effects as specified by
526      * {@link VarHandle#compareAndExchangeAcquire}.
527      *
528      * @param expectedValue the expected value
529      * @param newValue the new value
530      * @return the witness value, which will be the same as the
531      * expected value if successful
532      * @since 9
533      */
compareAndExchangeAcquire(int expectedValue, int newValue)534     public final int compareAndExchangeAcquire(int expectedValue, int newValue) {
535         // Android-changed: Using VarHandle instead of Unsafe
536         // return U.compareAndExchangeIntAcquire(this, VALUE, expectedValue, newValue);
537         return (int)VALUE.compareAndExchangeAcquire(this, expectedValue, newValue);
538     }
539 
540     /**
541      * Atomically sets the value to {@code newValue} if the current value,
542      * referred to as the <em>witness value</em>, {@code == expectedValue},
543      * with memory effects as specified by
544      * {@link VarHandle#compareAndExchangeRelease}.
545      *
546      * @param expectedValue the expected value
547      * @param newValue the new value
548      * @return the witness value, which will be the same as the
549      * expected value if successful
550      * @since 9
551      */
compareAndExchangeRelease(int expectedValue, int newValue)552     public final int compareAndExchangeRelease(int expectedValue, int newValue) {
553         // Android-changed: Using VarHandle instead of Unsafe
554         // return U.compareAndExchangeIntRelease(this, VALUE, expectedValue, newValue);
555         return (int)VALUE.compareAndExchangeRelease(this, expectedValue, newValue);
556     }
557 
558     /**
559      * Possibly atomically sets the value to {@code newValue} if
560      * the current value {@code == expectedValue},
561      * with memory effects as specified by
562      * {@link VarHandle#weakCompareAndSet}.
563      *
564      * @param expectedValue the expected value
565      * @param newValue the new value
566      * @return {@code true} if successful
567      * @since 9
568      */
weakCompareAndSetVolatile(int expectedValue, int newValue)569     public final boolean weakCompareAndSetVolatile(int expectedValue, int newValue) {
570         // Android-changed: Using VarHandle instead of Unsafe
571         //return U.weakCompareAndSetInt(this, VALUE, expectedValue, newValue);
572         return VALUE.weakCompareAndSet(this, expectedValue, newValue);
573     }
574 
575     /**
576      * Possibly atomically sets the value to {@code newValue} if
577      * the current value {@code == expectedValue},
578      * with memory effects as specified by
579      * {@link VarHandle#weakCompareAndSetAcquire}.
580      *
581      * @param expectedValue the expected value
582      * @param newValue the new value
583      * @return {@code true} if successful
584      * @since 9
585      */
weakCompareAndSetAcquire(int expectedValue, int newValue)586     public final boolean weakCompareAndSetAcquire(int expectedValue, int newValue) {
587         // Android-changed: Using VarHandle instead of Unsafe
588         // return U.weakCompareAndSetIntAcquire(this, VALUE, expectedValue, newValue);
589         return VALUE.weakCompareAndSetAcquire(this, expectedValue, newValue);
590     }
591 
592     /**
593      * Possibly atomically sets the value to {@code newValue} if
594      * the current value {@code == expectedValue},
595      * with memory effects as specified by
596      * {@link VarHandle#weakCompareAndSetRelease}.
597      *
598      * @param expectedValue the expected value
599      * @param newValue the new value
600      * @return {@code true} if successful
601      * @since 9
602      */
weakCompareAndSetRelease(int expectedValue, int newValue)603     public final boolean weakCompareAndSetRelease(int expectedValue, int newValue) {
604         // Android-changed: Using VarHandle instead of Unsafe
605         // return U.weakCompareAndSetIntRelease(this, VALUE, expectedValue, newValue);
606         return VALUE.weakCompareAndSetRelease(this, expectedValue, newValue);
607     }
608 
609 }
610