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 AtomicLong instead of sun.misc.Unsafe)
013 */
014
015package com.google.common.util.concurrent;
016
017import static java.lang.Double.doubleToRawLongBits;
018import static java.lang.Double.longBitsToDouble;
019
020import com.google.errorprone.annotations.CanIgnoreReturnValue;
021import java.util.concurrent.atomic.AtomicLong;
022
023/**
024 * A {@code double} value that may be updated atomically. See the {@link
025 * java.util.concurrent.atomic} package specification for description of the properties of atomic
026 * variables. An {@code AtomicDouble} is used in applications such as atomic accumulation, and
027 * cannot be used as a replacement for a {@link Double}. However, this class does extend {@code
028 * Number} to allow uniform access by tools and utilities that deal with numerically-based classes.
029 *
030 * <p><a name="bitEquals"></a>This class compares primitive {@code double} values in methods such as
031 * {@link #compareAndSet} by comparing their bitwise representation using {@link
032 * Double#doubleToRawLongBits}, which differs from both the primitive double {@code ==} operator and
033 * from {@link Double#equals}, as if implemented by:
034 *
035 * <pre>{@code
036 * static boolean bitEquals(double x, double y) {
037 *   long xBits = Double.doubleToRawLongBits(x);
038 *   long yBits = Double.doubleToRawLongBits(y);
039 *   return xBits == yBits;
040 * }
041 * }</pre>
042 *
043 * <p>It is possible to write a more scalable updater, at the cost of giving up strict atomicity.
044 * See for example <a
045 * href="http://gee.cs.oswego.edu/dl/jsr166/dist/jsr166edocs/jsr166e/DoubleAdder.html">
046 * DoubleAdder</a> and <a
047 * href="http://gee.cs.oswego.edu/dl/jsr166/dist/jsr166edocs/jsr166e/DoubleMaxUpdater.html">
048 * DoubleMaxUpdater</a>.
049 *
050 * @author Doug Lea
051 * @author Martin Buchholz
052 * @since 11.0
053 */
054public class AtomicDouble extends Number implements java.io.Serializable {
055  private static final long serialVersionUID = 0L;
056
057  // We would use AtomicLongFieldUpdater, but it has issues on some Android devices.
058  private transient AtomicLong value;
059
060  /**
061   * Creates a new {@code AtomicDouble} with the given initial value.
062   *
063   * @param initialValue the initial value
064   */
065  public AtomicDouble(double initialValue) {
066    value = new AtomicLong(doubleToRawLongBits(initialValue));
067  }
068
069  /**
070   * Creates a new {@code AtomicDouble} with initial value {@code 0.0}.
071   */
072  public AtomicDouble() {
073    this(0.0);
074  }
075
076  /**
077   * Gets the current value.
078   *
079   * @return the current value
080   */
081  public final double get() {
082    return longBitsToDouble(value.get());
083  }
084
085  /**
086   * Sets to the given value.
087   *
088   * @param newValue the new value
089   */
090  public final void set(double newValue) {
091    long next = doubleToRawLongBits(newValue);
092    value.set(next);
093  }
094
095  /**
096   * Eventually sets to the given value.
097   *
098   * @param newValue the new value
099   */
100  public final void lazySet(double newValue) {
101    long next = doubleToRawLongBits(newValue);
102    value.lazySet(next);
103  }
104
105  /**
106   * Atomically sets to the given value and returns the old value.
107   *
108   * @param newValue the new value
109   * @return the previous value
110   */
111  public final double getAndSet(double newValue) {
112    long next = doubleToRawLongBits(newValue);
113    return longBitsToDouble(value.getAndSet(next));
114  }
115
116  /**
117   * Atomically sets the value to the given updated value
118   * if the current value is <a href="#bitEquals">bitwise equal</a>
119   * to the expected value.
120   *
121   * @param expect the expected value
122   * @param update the new value
123   * @return {@code true} if successful. False return indicates that
124   * the actual value was not bitwise equal to the expected value.
125   */
126  public final boolean compareAndSet(double expect, double update) {
127    return value.compareAndSet(
128                                 doubleToRawLongBits(expect),
129                                 doubleToRawLongBits(update));
130  }
131
132  /**
133   * Atomically sets the value to the given updated value
134   * if the current value is <a href="#bitEquals">bitwise equal</a>
135   * to the expected value.
136   *
137   * <p>May <a
138   * href="http://download.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/package-summary.html#Spurious">
139   * fail spuriously</a>
140   * and does not provide ordering guarantees, so is only rarely an
141   * appropriate alternative to {@code compareAndSet}.
142   *
143   * @param expect the expected value
144   * @param update the new value
145   * @return {@code true} if successful
146   */
147  public final boolean weakCompareAndSet(double expect, double update) {
148    return value.weakCompareAndSet(
149                                     doubleToRawLongBits(expect),
150                                     doubleToRawLongBits(update));
151  }
152
153  /**
154   * Atomically adds the given value to the current value.
155   *
156   * @param delta the value to add
157   * @return the previous value
158   */
159  @CanIgnoreReturnValue
160  public final double getAndAdd(double delta) {
161    while (true) {
162      long current = value.get();
163      double currentVal = longBitsToDouble(current);
164      double nextVal = currentVal + delta;
165      long next = doubleToRawLongBits(nextVal);
166      if (value.compareAndSet(current, next)) {
167        return currentVal;
168      }
169    }
170  }
171
172  /**
173   * Atomically adds the given value to the current value.
174   *
175   * @param delta the value to add
176   * @return the updated value
177   */
178  @CanIgnoreReturnValue
179  public final double addAndGet(double delta) {
180    while (true) {
181      long current = value.get();
182      double currentVal = longBitsToDouble(current);
183      double nextVal = currentVal + delta;
184      long next = doubleToRawLongBits(nextVal);
185      if (value.compareAndSet(current, next)) {
186        return nextVal;
187      }
188    }
189  }
190
191  /**
192   * Returns the String representation of the current value.
193   * @return the String representation of the current value
194   */
195  public String toString() {
196    return Double.toString(get());
197  }
198
199  /**
200   * Returns the value of this {@code AtomicDouble} as an {@code int}
201   * after a narrowing primitive conversion.
202   */
203  public int intValue() {
204    return (int) get();
205  }
206
207  /**
208   * Returns the value of this {@code AtomicDouble} as a {@code long}
209   * after a narrowing primitive conversion.
210   */
211  public long longValue() {
212    return (long) get();
213  }
214
215  /**
216   * Returns the value of this {@code AtomicDouble} as a {@code float}
217   * after a narrowing primitive conversion.
218   */
219  public float floatValue() {
220    return (float) get();
221  }
222
223  /**
224   * Returns the value of this {@code AtomicDouble} as a {@code double}.
225   */
226  public double doubleValue() {
227    return get();
228  }
229
230  /**
231   * Saves the state to a stream (that is, serializes it).
232   *
233   * @serialData The current value is emitted (a {@code double}).
234   */
235  private void writeObject(java.io.ObjectOutputStream s)
236      throws java.io.IOException {
237    s.defaultWriteObject();
238
239    s.writeDouble(get());
240  }
241
242  /**
243   * Reconstitutes the instance from a stream (that is, deserializes it).
244   */
245  private void readObject(java.io.ObjectInputStream s)
246      throws java.io.IOException, ClassNotFoundException {
247    s.defaultReadObject();
248    value = new AtomicLong();
249    set(s.readDouble());
250  }
251}