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