src/share/classes/java/util/concurrent/atomic/AtomicLong.java

Print this page
rev 5834 : Rename compareAndSet methods, add updateAndGet/getAndUpdate to AtomicReference, add tests
Reviewed-by: briangoetz,smarks,mduigo
Contributed-by: Jim Gish <jim.gish@oracle.com>

*** 158,177 **** * (using the new current value) until successful. * * @param op the operator to use to compute the new value * @return the new value */ ! public final long compareAndSet(LongUnaryOperator op) { long oldValue, newValue; do { oldValue = get(); newValue = op.operate(oldValue); } while (!compareAndSet(oldValue, newValue)); return newValue; } /** * Atomically sets the value to the given updated value * if the current value {@code ==} the expected value. * * <p>May <a href="package-summary.html#Spurious">fail spuriously</a> * and does not provide ordering guarantees, so is only rarely an --- 158,196 ---- * (using the new current value) until successful. * * @param op the operator to use to compute the new value * @return the new value */ ! public final long updateAndGet(LongUnaryOperator op) { long oldValue, newValue; do { oldValue = get(); newValue = op.operate(oldValue); } while (!compareAndSet(oldValue, newValue)); return newValue; } /** + * Sets the value by applying the supplied operator to the old value, + * and updating it atomically as in {@link #compareAndSet(long, long)}. + * + * If the update results in a collision, we back off and retry the update + * (using the new current value) until successful. + * + * @param op the operator to use to compute the new value + * @return the old value + */ + public final long getAndUpdate(LongUnaryOperator op) { + long oldValue, newValue; + do { + oldValue = get(); + newValue = op.operate(oldValue); + } while (!compareAndSet(oldValue, newValue)); + return oldValue; + } + + /** * Atomically sets the value to the given updated value * if the current value {@code ==} the expected value. * * <p>May <a href="package-summary.html#Spurious">fail spuriously</a> * and does not provide ordering guarantees, so is only rarely an