001/*
002 * Written by Doug Lea and Martin Buchholz with assistance from
003 * members of JCP JSR-166 Expert Group and released to the public
004 * domain, as explained at
005 * http://creativecommons.org/publicdomain/zero/1.0/
006 */
007
008/*
009 * Source:
010 * http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/jsr166e/extra/AtomicDouble.java?revision=1.13
011 * (Modified to adapt to guava coding conventions and
012 * to use AtomicLongFieldUpdater instead of sun.misc.Unsafe)
013 */
014
015package com.google.common.util.concurrent;
016
017import static com.google.common.base.Preconditions.checkNotNull;
018import static java.lang.Double.doubleToRawLongBits;
019import static java.lang.Double.longBitsToDouble;
020
021import com.google.common.annotations.GwtIncompatible;
022import com.google.common.annotations.J2ktIncompatible;
023import com.google.errorprone.annotations.CanIgnoreReturnValue;
024import com.google.j2objc.annotations.ReflectionSupport;
025import java.io.IOException;
026import java.io.ObjectInputStream;
027import java.io.ObjectOutputStream;
028import java.io.Serializable;
029import java.util.concurrent.atomic.AtomicLongFieldUpdater;
030import java.util.function.DoubleBinaryOperator;
031import java.util.function.DoubleUnaryOperator;
032
033/**
034 * A {@code double} value that may be updated atomically. See the {@link
035 * java.util.concurrent.atomic} package specification for description of the properties of atomic
036 * variables. An {@code AtomicDouble} is used in applications such as atomic accumulation, and
037 * cannot be used as a replacement for a {@link Double}. However, this class does extend {@code
038 * Number} to allow uniform access by tools and utilities that deal with numerically-based classes.
039 *
040 * <p><a id="bitEquals"></a>This class compares primitive {@code double} values in methods such as
041 * {@link #compareAndSet} by comparing their bitwise representation using {@link
042 * Double#doubleToRawLongBits}, which differs from both the primitive double {@code ==} operator and
043 * from {@link Double#equals}, as if implemented by:
044 *
045 * <pre>{@code
046 * static boolean bitEquals(double x, double y) {
047 *   long xBits = Double.doubleToRawLongBits(x);
048 *   long yBits = Double.doubleToRawLongBits(y);
049 *   return xBits == yBits;
050 * }
051 * }</pre>
052 *
053 * <p>It is possible to write a more scalable updater, at the cost of giving up strict atomicity.
054 * See for example <a
055 * href="http://gee.cs.oswego.edu/dl/jsr166/dist/docs/java.base/java/util/concurrent/atomic/DoubleAdder.html">
056 * DoubleAdder</a>.
057 *
058 * @author Doug Lea
059 * @author Martin Buchholz
060 * @since 11.0
061 */
062@GwtIncompatible
063@J2ktIncompatible
064@ReflectionSupport(value = ReflectionSupport.Level.FULL)
065@ElementTypesAreNonnullByDefault
066public class AtomicDouble extends Number implements Serializable {
067  private static final long serialVersionUID = 0L;
068
069  private transient volatile long value;
070
071  private static final AtomicLongFieldUpdater<AtomicDouble> updater =
072      AtomicLongFieldUpdater.newUpdater(AtomicDouble.class, "value");
073
074  /**
075   * Creates a new {@code AtomicDouble} with the given initial value.
076   *
077   * @param initialValue the initial value
078   */
079  public AtomicDouble(double initialValue) {
080    value = doubleToRawLongBits(initialValue);
081  }
082
083  /** Creates a new {@code AtomicDouble} with initial value {@code 0.0}. */
084  public AtomicDouble() {
085    // assert doubleToRawLongBits(0.0) == 0L;
086  }
087
088  /**
089   * Gets the current value.
090   *
091   * @return the current value
092   */
093  public final double get() {
094    return longBitsToDouble(value);
095  }
096
097  /**
098   * Sets to the given value.
099   *
100   * @param newValue the new value
101   */
102  public final void set(double newValue) {
103    long next = doubleToRawLongBits(newValue);
104    value = next;
105  }
106
107  /**
108   * Eventually sets to the given value.
109   *
110   * @param newValue the new value
111   */
112  public final void lazySet(double newValue) {
113    long next = doubleToRawLongBits(newValue);
114    updater.lazySet(this, next);
115  }
116
117  /**
118   * Atomically sets to the given value and returns the old value.
119   *
120   * @param newValue the new value
121   * @return the previous value
122   */
123  public final double getAndSet(double newValue) {
124    long next = doubleToRawLongBits(newValue);
125    return longBitsToDouble(updater.getAndSet(this, next));
126  }
127
128  /**
129   * Atomically sets the value to the given updated value if the current value is <a
130   * href="#bitEquals">bitwise equal</a> to the expected value.
131   *
132   * @param expect the expected value
133   * @param update the new value
134   * @return {@code true} if successful. False return indicates that the actual value was not
135   *     bitwise equal to the expected value.
136   */
137  public final boolean compareAndSet(double expect, double update) {
138    return updater.compareAndSet(this, doubleToRawLongBits(expect), doubleToRawLongBits(update));
139  }
140
141  /**
142   * Atomically sets the value to the given updated value if the current value is <a
143   * href="#bitEquals">bitwise equal</a> to the expected value.
144   *
145   * <p>May <a
146   * href="http://download.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/package-summary.html#Spurious">
147   * fail spuriously</a> and does not provide ordering guarantees, so is only rarely an appropriate
148   * alternative to {@code compareAndSet}.
149   *
150   * @param expect the expected value
151   * @param update the new value
152   * @return {@code true} if successful
153   */
154  public final boolean weakCompareAndSet(double expect, double update) {
155    return updater.weakCompareAndSet(
156        this, doubleToRawLongBits(expect), doubleToRawLongBits(update));
157  }
158
159  /**
160   * Atomically adds the given value to the current value.
161   *
162   * @param delta the value to add
163   * @return the previous value
164   */
165  @CanIgnoreReturnValue
166  public final double getAndAdd(double delta) {
167    return getAndAccumulate(delta, Double::sum);
168  }
169
170  /**
171   * Atomically adds the given value to the current value.
172   *
173   * @param delta the value to add
174   * @return the updated value
175   */
176  @CanIgnoreReturnValue
177  public final double addAndGet(double delta) {
178    return accumulateAndGet(delta, Double::sum);
179  }
180
181  /**
182   * Atomically updates the current value with the results of applying the given function to the
183   * current and given values.
184   *
185   * @param x the update value
186   * @param accumulatorFunction the accumulator function
187   * @return the previous value
188   * @since 31.1
189   */
190  @CanIgnoreReturnValue
191  public final double getAndAccumulate(double x, DoubleBinaryOperator accumulatorFunction) {
192    checkNotNull(accumulatorFunction);
193    return getAndUpdate(oldValue -> accumulatorFunction.applyAsDouble(oldValue, x));
194  }
195
196  /**
197   * Atomically updates the current value with the results of applying the given function to the
198   * current and given values.
199   *
200   * @param x the update value
201   * @param accumulatorFunction the accumulator function
202   * @return the updated value
203   * @since 31.1
204   */
205  @CanIgnoreReturnValue
206  public final double accumulateAndGet(double x, DoubleBinaryOperator accumulatorFunction) {
207    checkNotNull(accumulatorFunction);
208    return updateAndGet(oldValue -> accumulatorFunction.applyAsDouble(oldValue, x));
209  }
210
211  /**
212   * Atomically updates the current value with the results of applying the given function.
213   *
214   * @param updateFunction the update function
215   * @return the previous value
216   * @since 31.1
217   */
218  @CanIgnoreReturnValue
219  public final double getAndUpdate(DoubleUnaryOperator updateFunction) {
220    while (true) {
221      long current = value;
222      double currentVal = longBitsToDouble(current);
223      double nextVal = updateFunction.applyAsDouble(currentVal);
224      long next = doubleToRawLongBits(nextVal);
225      if (updater.compareAndSet(this, current, next)) {
226        return currentVal;
227      }
228    }
229  }
230
231  /**
232   * Atomically updates the current value with the results of applying the given function.
233   *
234   * @param updateFunction the update function
235   * @return the updated value
236   * @since 31.1
237   */
238  @CanIgnoreReturnValue
239  public final double updateAndGet(DoubleUnaryOperator updateFunction) {
240    while (true) {
241      long current = value;
242      double currentVal = longBitsToDouble(current);
243      double nextVal = updateFunction.applyAsDouble(currentVal);
244      long next = doubleToRawLongBits(nextVal);
245      if (updater.compareAndSet(this, current, next)) {
246        return nextVal;
247      }
248    }
249  }
250
251  /**
252   * Returns the String representation of the current value.
253   *
254   * @return the String representation of the current value
255   */
256  @Override
257  public String toString() {
258    return Double.toString(get());
259  }
260
261  /**
262   * Returns the value of this {@code AtomicDouble} as an {@code int} after a narrowing primitive
263   * conversion.
264   */
265  @Override
266  public int intValue() {
267    return (int) get();
268  }
269
270  /**
271   * Returns the value of this {@code AtomicDouble} as a {@code long} after a narrowing primitive
272   * conversion.
273   */
274  @Override
275  public long longValue() {
276    return (long) get();
277  }
278
279  /**
280   * Returns the value of this {@code AtomicDouble} as a {@code float} after a narrowing primitive
281   * conversion.
282   */
283  @Override
284  public float floatValue() {
285    return (float) get();
286  }
287
288  /** Returns the value of this {@code AtomicDouble} as a {@code double}. */
289  @Override
290  public double doubleValue() {
291    return get();
292  }
293
294  /**
295   * Saves the state to a stream (that is, serializes it).
296   *
297   * @serialData The current value is emitted (a {@code double}).
298   */
299  private void writeObject(ObjectOutputStream s) throws IOException {
300    s.defaultWriteObject();
301
302    s.writeDouble(get());
303  }
304
305  /** Reconstitutes the instance from a stream (that is, deserializes it). */
306  private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException {
307    s.defaultReadObject();
308
309    set(s.readDouble());
310  }
311}