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 java.lang.Double.doubleToRawLongBits; 017import static java.lang.Double.longBitsToDouble; 018 019import com.google.common.annotations.GwtIncompatible; 020import com.google.common.annotations.J2ktIncompatible; 021import com.google.common.primitives.ImmutableLongArray; 022import com.google.errorprone.annotations.CanIgnoreReturnValue; 023import java.io.IOException; 024import java.io.ObjectInputStream; 025import java.io.ObjectOutputStream; 026import java.io.Serializable; 027import java.util.concurrent.atomic.AtomicLongArray; 028 029/** 030 * A {@code double} array in which elements may be updated atomically. See the {@link 031 * java.util.concurrent.atomic} package specification for description of the properties of atomic 032 * variables. 033 * 034 * <p><a id="bitEquals"></a>This class compares primitive {@code double} values in methods such as 035 * {@link #compareAndSet} by comparing their bitwise representation using {@link 036 * Double#doubleToRawLongBits}, which differs from both the primitive double {@code ==} operator and 037 * from {@link Double#equals}, as if implemented by: 038 * 039 * <pre>{@code 040 * static boolean bitEquals(double x, double y) { 041 * long xBits = Double.doubleToRawLongBits(x); 042 * long yBits = Double.doubleToRawLongBits(y); 043 * return xBits == yBits; 044 * } 045 * }</pre> 046 * 047 * @author Doug Lea 048 * @author Martin Buchholz 049 * @since 11.0 050 */ 051@GwtIncompatible 052@J2ktIncompatible 053public class AtomicDoubleArray implements Serializable { 054 private static final long serialVersionUID = 0L; 055 056 // Making this non-final is the lesser evil according to Effective 057 // Java 2nd Edition Item 76: Write readObject methods defensively. 058 private transient AtomicLongArray longs; 059 060 /** 061 * Creates a new {@code AtomicDoubleArray} of the given length, with all elements initially zero. 062 * 063 * @param length the length of the array 064 */ 065 public AtomicDoubleArray(int length) { 066 this.longs = new AtomicLongArray(length); 067 } 068 069 /** 070 * Creates a new {@code AtomicDoubleArray} with the same length as, and all elements copied from, 071 * the given array. 072 * 073 * @param array the array to copy elements from 074 * @throws NullPointerException if array is null 075 */ 076 public AtomicDoubleArray(double[] array) { 077 int len = array.length; 078 long[] longArray = new long[len]; 079 for (int i = 0; i < len; i++) { 080 longArray[i] = doubleToRawLongBits(array[i]); 081 } 082 this.longs = new AtomicLongArray(longArray); 083 } 084 085 /** 086 * Returns the length of the array. 087 * 088 * @return the length of the array 089 */ 090 public final int length() { 091 return longs.length(); 092 } 093 094 /** 095 * Gets the current value at position {@code i}. 096 * 097 * @param i the index 098 * @return the current value 099 */ 100 public final double get(int i) { 101 return longBitsToDouble(longs.get(i)); 102 } 103 104 /** 105 * Atomically sets the element at position {@code i} to the given value. 106 * 107 * @param i the index 108 * @param newValue the new value 109 */ 110 public final void set(int i, double newValue) { 111 long next = doubleToRawLongBits(newValue); 112 longs.set(i, next); 113 } 114 115 /** 116 * Eventually sets the element at position {@code i} to the given value. 117 * 118 * @param i the index 119 * @param newValue the new value 120 */ 121 public final void lazySet(int i, double newValue) { 122 long next = doubleToRawLongBits(newValue); 123 longs.lazySet(i, next); 124 } 125 126 /** 127 * Atomically sets the element at position {@code i} to the given value and returns the old value. 128 * 129 * @param i the index 130 * @param newValue the new value 131 * @return the previous value 132 */ 133 public final double getAndSet(int i, double newValue) { 134 long next = doubleToRawLongBits(newValue); 135 return longBitsToDouble(longs.getAndSet(i, next)); 136 } 137 138 /** 139 * Atomically sets the element at position {@code i} to the given updated value if the current 140 * value is <a href="#bitEquals">bitwise equal</a> to the expected value. 141 * 142 * @param i the index 143 * @param expect the expected value 144 * @param update the new value 145 * @return true if successful. False return indicates that the actual value was not equal to the 146 * expected value. 147 */ 148 public final boolean compareAndSet(int i, double expect, double update) { 149 return longs.compareAndSet(i, doubleToRawLongBits(expect), doubleToRawLongBits(update)); 150 } 151 152 /** 153 * Atomically sets the element at position {@code i} to the given updated value if the current 154 * value is <a href="#bitEquals">bitwise equal</a> to the expected value. 155 * 156 * <p>May <a 157 * href="http://download.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/package-summary.html#Spurious"> 158 * fail spuriously</a> and does not provide ordering guarantees, so is only rarely an appropriate 159 * alternative to {@code compareAndSet}. 160 * 161 * @param i the index 162 * @param expect the expected value 163 * @param update the new value 164 * @return true if successful 165 */ 166 public final boolean weakCompareAndSet(int i, double expect, double update) { 167 return longs.weakCompareAndSet(i, doubleToRawLongBits(expect), doubleToRawLongBits(update)); 168 } 169 170 /** 171 * Atomically adds the given value to the element at index {@code i}. 172 * 173 * @param i the index 174 * @param delta the value to add 175 * @return the previous value 176 */ 177 @CanIgnoreReturnValue 178 public final double getAndAdd(int i, double delta) { 179 while (true) { 180 long current = longs.get(i); 181 double currentVal = longBitsToDouble(current); 182 double nextVal = currentVal + delta; 183 long next = doubleToRawLongBits(nextVal); 184 if (longs.compareAndSet(i, current, next)) { 185 return currentVal; 186 } 187 } 188 } 189 190 /** 191 * Atomically adds the given value to the element at index {@code i}. 192 * 193 * @param i the index 194 * @param delta the value to add 195 * @return the updated value 196 * @since 31.1 197 */ 198 @CanIgnoreReturnValue 199 public double addAndGet(int i, double delta) { 200 while (true) { 201 long current = longs.get(i); 202 double currentVal = longBitsToDouble(current); 203 double nextVal = currentVal + delta; 204 long next = doubleToRawLongBits(nextVal); 205 if (longs.compareAndSet(i, current, next)) { 206 return nextVal; 207 } 208 } 209 } 210 211 /** 212 * Returns the String representation of the current values of array. 213 * 214 * @return the String representation of the current values of array 215 */ 216 @Override 217 public String toString() { 218 int iMax = length() - 1; 219 if (iMax == -1) { 220 return "[]"; 221 } 222 223 // Double.toString(Math.PI).length() == 17 224 StringBuilder b = new StringBuilder((17 + 2) * (iMax + 1)); 225 b.append('['); 226 for (int i = 0; ; i++) { 227 b.append(longBitsToDouble(longs.get(i))); 228 if (i == iMax) { 229 return b.append(']').toString(); 230 } 231 b.append(',').append(' '); 232 } 233 } 234 235 /** 236 * Saves the state to a stream (that is, serializes it). 237 * 238 * @serialData The length of the array is emitted (int), followed by all of its elements (each a 239 * {@code double}) in the proper order. 240 */ 241 private void writeObject(ObjectOutputStream s) throws IOException { 242 s.defaultWriteObject(); 243 244 // Write out array length 245 int length = length(); 246 s.writeInt(length); 247 248 // Write out all elements in the proper order. 249 for (int i = 0; i < length; i++) { 250 s.writeDouble(get(i)); 251 } 252 } 253 254 /** Reconstitutes the instance from a stream (that is, deserializes it). */ 255 private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { 256 s.defaultReadObject(); 257 258 int length = s.readInt(); 259 ImmutableLongArray.Builder builder = ImmutableLongArray.builder(); 260 for (int i = 0; i < length; i++) { 261 builder.add(doubleToRawLongBits(s.readDouble())); 262 } 263 this.longs = new AtomicLongArray(builder.build().toArray()); 264 } 265}