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