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         // Use putLongVolatile instead of ordinary volatile store when
 113         // using compareAndSetLong, for sake of some 32bit systems.
 114         U.putLongVolatile(this, VALUE, newValue);
 115     }
 116 
 117     /**
 118      * Sets the value to {@code newValue},
 119      * with memory effects as specified by {@link VarHandle#setRelease}.
 120      *
 121      * @param newValue the new value
 122      * @since 1.6
 123      */
 124     public final void lazySet(long newValue) {
 125         U.putLongRelease(this, VALUE, newValue);
 126     }
 127 
 128     /**
 129      * Atomically sets the value to {@code newValue} and returns the old value,
 130      * with memory effects as specified by {@link VarHandle#getAndSet}.
 131      *
 132      * @param newValue the new value
 133      * @return the previous value
 134      */
 135     public final long getAndSet(long newValue) {
 136         return U.getAndSetLong(this, VALUE, 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      */
 149     public final boolean compareAndSet(long expectedValue, long newValue) {
 150         return U.compareAndSetLong(this, VALUE, expectedValue, newValue);
 151     }
 152 
 153     /**
 154      * Possibly atomically sets the value to {@code newValue}
 155      * if the current value {@code == expectedValue},
 156      * with memory effects as specified by {@link VarHandle#weakCompareAndSetPlain}.
 157      *
 158      * @deprecated This method has plain memory effects but the method
 159      * name implies volatile memory effects (see methods such as
 160      * {@link #compareAndExchange} and {@link #compareAndSet}).  To avoid
 161      * confusion over plain or volatile memory effects it is recommended that
 162      * the method {@link #weakCompareAndSetPlain} be used instead.
 163      *
 164      * @param expectedValue the expected value
 165      * @param newValue the new value
 166      * @return {@code true} if successful
 167      * @see #weakCompareAndSetPlain
 168      */
 169     @Deprecated(since="9")
 170     public final boolean weakCompareAndSet(long expectedValue, long newValue) {
 171         return U.weakCompareAndSetLongPlain(this, VALUE, expectedValue, newValue);
 172     }
 173 
 174     /**
 175      * Possibly atomically sets the value to {@code newValue}
 176      * if the current value {@code == expectedValue},
 177      * with memory effects as specified by {@link VarHandle#weakCompareAndSetPlain}.
 178      *
 179      * @param expectedValue the expected value
 180      * @param newValue the new value
 181      * @return {@code true} if successful
 182      * @since 9
 183      */
 184     public final boolean weakCompareAndSetPlain(long expectedValue, long newValue) {
 185         return U.weakCompareAndSetLongPlain(this, VALUE, expectedValue, newValue);
 186     }
 187 
 188     /**
 189      * Atomically increments the current value,
 190      * with memory effects as specified by {@link VarHandle#getAndAdd}.
 191      *
 192      * <p>Equivalent to {@code getAndAdd(1)}.
 193      *
 194      * @return the previous value
 195      */
 196     public final long getAndIncrement() {
 197         return U.getAndAddLong(this, VALUE, 1L);
 198     }
 199 
 200     /**
 201      * Atomically decrements the current value,
 202      * with memory effects as specified by {@link VarHandle#getAndAdd}.
 203      *
 204      * <p>Equivalent to {@code getAndAdd(-1)}.
 205      *
 206      * @return the previous value
 207      */
 208     public final long getAndDecrement() {
 209         return U.getAndAddLong(this, VALUE, -1L);
 210     }
 211 
 212     /**
 213      * Atomically adds the given value to the current value,
 214      * with memory effects as specified by {@link VarHandle#getAndAdd}.
 215      *
 216      * @param delta the value to add
 217      * @return the previous value
 218      */
 219     public final long getAndAdd(long delta) {
 220         return U.getAndAddLong(this, VALUE, delta);
 221     }
 222 
 223     /**
 224      * Atomically increments the current value,
 225      * with memory effects as specified by {@link VarHandle#getAndAdd}.
 226      *
 227      * <p>Equivalent to {@code addAndGet(1)}.
 228      *
 229      * @return the updated value
 230      */
 231     public final long incrementAndGet() {
 232         return U.getAndAddLong(this, VALUE, 1L) + 1L;
 233     }
 234 
 235     /**
 236      * Atomically decrements 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      */
 243     public final long decrementAndGet() {
 244         return U.getAndAddLong(this, VALUE, -1L) - 1L;
 245     }
 246 
 247     /**
 248      * Atomically adds the given value to the current value,
 249      * with memory effects as specified by {@link VarHandle#getAndAdd}.
 250      *
 251      * @param delta the value to add
 252      * @return the updated value
 253      */
 254     public final long addAndGet(long delta) {
 255         return U.getAndAddLong(this, VALUE, delta) + delta;
 256     }
 257 
 258     /**
 259      * Atomically updates 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 the current value with the results of
 281      * applying the given function, returning the updated value. The
 282      * function should be side-effect-free, since it may be re-applied
 283      * when attempted updates fail due to contention among threads.
 284      *
 285      * @param updateFunction a side-effect-free function
 286      * @return the updated value
 287      * @since 1.8
 288      */
 289     public final long updateAndGet(LongUnaryOperator updateFunction) {
 290         long prev = get(), next = 0L;
 291         for (boolean haveNext = false;;) {
 292             if (!haveNext)
 293                 next = updateFunction.applyAsLong(prev);
 294             if (weakCompareAndSetVolatile(prev, next))
 295                 return next;
 296             haveNext = (prev == (prev = get()));
 297         }
 298     }
 299 
 300     /**
 301      * Atomically updates the current value with the results of
 302      * applying the given function to the current and given values,
 303      * returning the previous value. The function should be
 304      * side-effect-free, since it may be re-applied when attempted
 305      * updates fail due to contention among threads.  The function
 306      * is applied with the current value as its first argument,
 307      * and the given update as the second argument.
 308      *
 309      * @param x the update value
 310      * @param accumulatorFunction a side-effect-free function of two arguments
 311      * @return the previous value
 312      * @since 1.8
 313      */
 314     public final long getAndAccumulate(long x,
 315                                        LongBinaryOperator accumulatorFunction) {
 316         long prev = get(), next = 0L;
 317         for (boolean haveNext = false;;) {
 318             if (!haveNext)
 319                 next = accumulatorFunction.applyAsLong(prev, x);
 320             if (weakCompareAndSetVolatile(prev, next))
 321                 return prev;
 322             haveNext = (prev == (prev = get()));
 323         }
 324     }
 325 
 326     /**
 327      * Atomically updates the current value with the results of
 328      * applying the given function to the current and given values,
 329      * returning the updated value. The function should be
 330      * side-effect-free, since it may be re-applied when attempted
 331      * updates fail due to contention among threads.  The function
 332      * is applied with the current value as its first argument,
 333      * and the given update as the second argument.
 334      *
 335      * @param x the update value
 336      * @param accumulatorFunction a side-effect-free function of two arguments
 337      * @return the updated value
 338      * @since 1.8
 339      */
 340     public final long accumulateAndGet(long x,
 341                                        LongBinaryOperator accumulatorFunction) {
 342         long prev = get(), next = 0L;
 343         for (boolean haveNext = false;;) {
 344             if (!haveNext)
 345                 next = accumulatorFunction.applyAsLong(prev, x);
 346             if (weakCompareAndSetVolatile(prev, next))
 347                 return next;
 348             haveNext = (prev == (prev = get()));
 349         }
 350     }
 351 
 352     /**
 353      * Returns the String representation of the current value.
 354      * @return the String representation of the current value
 355      */
 356     public String toString() {
 357         return Long.toString(get());
 358     }
 359 
 360     /**
 361      * Returns the current value of this {@code AtomicLong} as an {@code int}
 362      * after a narrowing primitive conversion,
 363      * with memory effects as specified by {@link VarHandle#getVolatile}.
 364      * @jls 5.1.3 Narrowing Primitive Conversions
 365      */
 366     public int intValue() {
 367         return (int)get();
 368     }
 369 
 370     /**
 371      * Returns the current value of this {@code AtomicLong} as a {@code long},
 372      * with memory effects as specified by {@link VarHandle#getVolatile}.
 373      * Equivalent to {@link #get()}.
 374      */
 375     public long longValue() {
 376         return get();
 377     }
 378 
 379     /**
 380      * Returns the current value of this {@code AtomicLong} as a {@code float}
 381      * after a widening primitive conversion,
 382      * with memory effects as specified by {@link VarHandle#getVolatile}.
 383      * @jls 5.1.2 Widening Primitive Conversions
 384      */
 385     public float floatValue() {
 386         return (float)get();
 387     }
 388 
 389     /**
 390      * Returns the current value of this {@code AtomicLong} as a {@code double}
 391      * after a widening primitive conversion,
 392      * with memory effects as specified by {@link VarHandle#getVolatile}.
 393      * @jls 5.1.2 Widening Primitive Conversions
 394      */
 395     public double doubleValue() {
 396         return (double)get();
 397     }
 398 
 399     // jdk9
 400 
 401     /**
 402      * Returns the current value, with memory semantics of reading as if the
 403      * variable was declared non-{@code volatile}.
 404      *
 405      * @return the value
 406      * @since 9
 407      */
 408     public final long getPlain() {
 409         return U.getLong(this, VALUE);
 410     }
 411 
 412     /**
 413      * Sets the value to {@code newValue}, with memory semantics
 414      * of setting as if the variable was declared non-{@code volatile}
 415      * and non-{@code final}.
 416      *
 417      * @param newValue the new value
 418      * @since 9
 419      */
 420     public final void setPlain(long newValue) {
 421         U.putLong(this, VALUE, newValue);
 422     }
 423 
 424     /**
 425      * Returns the current value,
 426      * with memory effects as specified by {@link VarHandle#getOpaque}.
 427      *
 428      * @return the value
 429      * @since 9
 430      */
 431     public final long getOpaque() {
 432         return U.getLongOpaque(this, VALUE);
 433     }
 434 
 435     /**
 436      * Sets the value to {@code newValue},
 437      * with memory effects as specified by {@link VarHandle#setOpaque}.
 438      *
 439      * @param newValue the new value
 440      * @since 9
 441      */
 442     public final void setOpaque(long newValue) {
 443         U.putLongOpaque(this, VALUE, newValue);
 444     }
 445 
 446     /**
 447      * Returns the current value,
 448      * with memory effects as specified by {@link VarHandle#getAcquire}.
 449      *
 450      * @return the value
 451      * @since 9
 452      */
 453     public final long getAcquire() {
 454         return U.getLongAcquire(this, VALUE);
 455     }
 456 
 457     /**
 458      * Sets the value to {@code newValue},
 459      * with memory effects as specified by {@link VarHandle#setRelease}.
 460      *
 461      * @param newValue the new value
 462      * @since 9
 463      */
 464     public final void setRelease(long newValue) {
 465         U.putLongRelease(this, VALUE, newValue);
 466     }
 467 
 468     /**
 469      * Atomically sets the value to {@code newValue} if the current value,
 470      * referred to as the <em>witness value</em>, {@code == expectedValue},
 471      * with memory effects as specified by
 472      * {@link VarHandle#compareAndExchange}.
 473      *
 474      * @param expectedValue the expected value
 475      * @param newValue the new value
 476      * @return the witness value, which will be the same as the
 477      * expected value if successful
 478      * @since 9
 479      */
 480     public final long compareAndExchange(long expectedValue, long newValue) {
 481         return U.compareAndExchangeLong(this, VALUE, expectedValue, newValue);
 482     }
 483 
 484     /**
 485      * Atomically sets the value to {@code newValue} if the current value,
 486      * referred to as the <em>witness value</em>, {@code == expectedValue},
 487      * with memory effects as specified by
 488      * {@link VarHandle#compareAndExchangeAcquire}.
 489      *
 490      * @param expectedValue the expected value
 491      * @param newValue the new value
 492      * @return the witness value, which will be the same as the
 493      * expected value if successful
 494      * @since 9
 495      */
 496     public final long compareAndExchangeAcquire(long expectedValue, long newValue) {
 497         return U.compareAndExchangeLongAcquire(this, VALUE, expectedValue, newValue);
 498     }
 499 
 500     /**
 501      * Atomically sets the value to {@code newValue} if the current value,
 502      * referred to as the <em>witness value</em>, {@code == expectedValue},
 503      * with memory effects as specified by
 504      * {@link VarHandle#compareAndExchangeRelease}.
 505      *
 506      * @param expectedValue the expected value
 507      * @param newValue the new value
 508      * @return the witness value, which will be the same as the
 509      * expected value if successful
 510      * @since 9
 511      */
 512     public final long compareAndExchangeRelease(long expectedValue, long newValue) {
 513         return U.compareAndExchangeLongRelease(this, VALUE, expectedValue, newValue);
 514     }
 515 
 516     /**
 517      * Possibly atomically sets the value to {@code newValue}
 518      * if the current value {@code == expectedValue},
 519      * with memory effects as specified by
 520      * {@link VarHandle#weakCompareAndSet}.
 521      *
 522      * @param expectedValue the expected value
 523      * @param newValue the new value
 524      * @return {@code true} if successful
 525      * @since 9
 526      */
 527     public final boolean weakCompareAndSetVolatile(long expectedValue, long newValue) {
 528         return U.weakCompareAndSetLong(this, VALUE, expectedValue, newValue);
 529     }
 530 
 531     /**
 532      * Possibly atomically sets the value to {@code newValue}
 533      * if the current value {@code == expectedValue},
 534      * with memory effects as specified by
 535      * {@link VarHandle#weakCompareAndSetAcquire}.
 536      *
 537      * @param expectedValue the expected value
 538      * @param newValue the new value
 539      * @return {@code true} if successful
 540      * @since 9
 541      */
 542     public final boolean weakCompareAndSetAcquire(long expectedValue, long newValue) {
 543         return U.weakCompareAndSetLongAcquire(this, VALUE, expectedValue, newValue);
 544     }
 545 
 546     /**
 547      * Possibly atomically sets the value to {@code newValue}
 548      * if the current value {@code == expectedValue},
 549      * with memory effects as specified by
 550      * {@link VarHandle#weakCompareAndSetRelease}.
 551      *
 552      * @param expectedValue the expected value
 553      * @param newValue the new value
 554      * @return {@code true} if successful
 555      * @since 9
 556      */
 557     public final boolean weakCompareAndSetRelease(long expectedValue, long newValue) {
 558         return U.weakCompareAndSetLongRelease(this, VALUE, expectedValue, newValue);
 559     }
 560 
 561 }