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 id="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/docs/java.base/java/util/concurrent/atomic/DoubleAdder.html">
046 * DoubleAdder</a>.
047 *
048 * @author Doug Lea
049 * @author Martin Buchholz
050 * @since 11.0
051 */
052public class AtomicDouble extends Number implements java.io.Serializable {
053  private static final long serialVersionUID = 0L;
054
055  // We would use AtomicLongFieldUpdater, but it has issues on some Android devices.
056  private transient AtomicLong value;
057
058  /**
059   * Creates a new {@code AtomicDouble} with the given initial value.
060   *
061   * @param initialValue the initial value
062   */
063  public AtomicDouble(double initialValue) {
064    value = new AtomicLong(doubleToRawLongBits(initialValue));
065  }
066
067  /** Creates a new {@code AtomicDouble} with initial value {@code 0.0}. */
068  public AtomicDouble() {
069    this(0.0);
070  }
071
072  /**
073   * Gets the current value.
074   *
075   * @return the current value
076   */
077  public final double get() {
078    return longBitsToDouble(value.get());
079  }
080
081  /**
082   * Sets to the given value.
083   *
084   * @param newValue the new value
085   */
086  public final void set(double newValue) {
087    long next = doubleToRawLongBits(newValue);
088    value.set(next);
089  }
090
091  /**
092   * Eventually sets to the given value.
093   *
094   * @param newValue the new value
095   */
096  public final void lazySet(double newValue) {
097    long next = doubleToRawLongBits(newValue);
098    value.lazySet(next);
099  }
100
101  /**
102   * Atomically sets to the given value and returns the old value.
103   *
104   * @param newValue the new value
105   * @return the previous value
106   */
107  public final double getAndSet(double newValue) {
108    long next = doubleToRawLongBits(newValue);
109    return longBitsToDouble(value.getAndSet(next));
110  }
111
112  /**
113   * Atomically sets the value to the given updated value if the current value is <a
114   * href="#bitEquals">bitwise equal</a> to the expected value.
115   *
116   * @param expect the expected value
117   * @param update the new value
118   * @return {@code true} if successful. False return indicates that the actual value was not
119   *     bitwise equal to the expected value.
120   */
121  public final boolean compareAndSet(double expect, double update) {
122    return value.compareAndSet(doubleToRawLongBits(expect), doubleToRawLongBits(update));
123  }
124
125  /**
126   * Atomically sets the value to the given updated value if the current value is <a
127   * href="#bitEquals">bitwise equal</a> to the expected value.
128   *
129   * <p>May <a
130   * href="http://download.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/package-summary.html#Spurious">
131   * fail spuriously</a> and does not provide ordering guarantees, so is only rarely an appropriate
132   * alternative to {@code compareAndSet}.
133   *
134   * @param expect the expected value
135   * @param update the new value
136   * @return {@code true} if successful
137   */
138  public final boolean weakCompareAndSet(double expect, double update) {
139    return value.weakCompareAndSet(doubleToRawLongBits(expect), doubleToRawLongBits(update));
140  }
141
142  /**
143   * Atomically adds the given value to the current value.
144   *
145   * @param delta the value to add
146   * @return the previous value
147   */
148  @CanIgnoreReturnValue
149  public final double getAndAdd(double delta) {
150    while (true) {
151      long current = value.get();
152      double currentVal = longBitsToDouble(current);
153      double nextVal = currentVal + delta;
154      long next = doubleToRawLongBits(nextVal);
155      if (value.compareAndSet(current, next)) {
156        return currentVal;
157      }
158    }
159  }
160
161  /**
162   * Atomically adds the given value to the current value.
163   *
164   * @param delta the value to add
165   * @return the updated value
166   */
167  @CanIgnoreReturnValue
168  public final double addAndGet(double delta) {
169    while (true) {
170      long current = value.get();
171      double currentVal = longBitsToDouble(current);
172      double nextVal = currentVal + delta;
173      long next = doubleToRawLongBits(nextVal);
174      if (value.compareAndSet(current, next)) {
175        return nextVal;
176      }
177    }
178  }
179
180  /**
181   * Returns the String representation of the current value.
182   *
183   * @return the String representation of the current value
184   */
185  @Override
186  public String toString() {
187    return Double.toString(get());
188  }
189
190  /**
191   * Returns the value of this {@code AtomicDouble} as an {@code int} after a narrowing primitive
192   * conversion.
193   */
194  @Override
195  public int intValue() {
196    return (int) get();
197  }
198
199  /**
200   * Returns the value of this {@code AtomicDouble} as a {@code long} after a narrowing primitive
201   * conversion.
202   */
203  @Override
204  public long longValue() {
205    return (long) get();
206  }
207
208  /**
209   * Returns the value of this {@code AtomicDouble} as a {@code float} after a narrowing primitive
210   * conversion.
211   */
212  @Override
213  public float floatValue() {
214    return (float) get();
215  }
216
217  /** Returns the value of this {@code AtomicDouble} as a {@code double}. */
218  @Override
219  public double doubleValue() {
220    return get();
221  }
222
223  /**
224   * Saves the state to a stream (that is, serializes it).
225   *
226   * @serialData The current value is emitted (a {@code double}).
227   */
228  private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException {
229    s.defaultWriteObject();
230
231    s.writeDouble(get());
232  }
233
234  /** Reconstitutes the instance from a stream (that is, deserializes it). */
235  private void readObject(java.io.ObjectInputStream s)
236      throws java.io.IOException, ClassNotFoundException {
237    s.defaultReadObject();
238    value = new AtomicLong();
239    set(s.readDouble());
240  }
241}