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