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