1 /* 2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 3 * 4 * This code is free software; you can redistribute it and/or modify it 5 * under the terms of the GNU General Public License version 2 only, as 6 * published by the Free Software Foundation. Oracle designates this 7 * particular file as subject to the "Classpath" exception as provided 8 * by Oracle in the LICENSE file that accompanied this code. 9 * 10 * This code is distributed in the hope that it will be useful, but WITHOUT 11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 13 * version 2 for more details (a copy is included in the LICENSE file that 14 * accompanied this code). 15 * 16 * You should have received a copy of the GNU General Public License version 17 * 2 along with this work; if not, write to the Free Software Foundation, 18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 19 * 20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 21 * or visit www.oracle.com if you need additional information or have any 22 * questions. 23 */ 24 25 /* 26 * This file is available under and governed by the GNU General Public 27 * License version 2 only, as published by the Free Software Foundation. 28 * However, the following notice accompanied the original version of this 29 * file: 30 * 31 * Written by Doug Lea with assistance from members of JCP JSR-166 32 * Expert Group and released to the public domain, as explained at 33 * http://creativecommons.org/publicdomain/zero/1.0/ 34 */ 35 36 package java.util.concurrent.atomic; 37 38 import java.io.Serializable; 39 40 /** 41 * One or more variables that together maintain an initially zero 42 * {@code double} sum. When updates (method {@link #add}) are 43 * contended across threads, the set of variables may grow dynamically 44 * to reduce contention. Method {@link #sum} (or, equivalently {@link 45 * #doubleValue}) returns the current total combined across the 46 * variables maintaining the sum. The order of accumulation within or 47 * across threads is not guaranteed. Thus, this class may not be 48 * applicable if numerical stability is required, especially when 49 * combining values of substantially different orders of magnitude. 50 * 51 * <p>This class is usually preferable to alternatives when multiple 52 * threads update a common value that is used for purposes such as 53 * summary statistics that are frequently updated but less frequently 54 * read. 55 * 56 * <p>This class extends {@link Number}, but does <em>not</em> define 57 * methods such as {@code equals}, {@code hashCode} and {@code 58 * compareTo} because instances are expected to be mutated, and so are 59 * not useful as collection keys. 60 * 61 * @since 1.8 62 * @author Doug Lea 63 */ 64 public class DoubleAdder extends Striped64 implements Serializable { 65 private static final long serialVersionUID = 7249069246863182397L; 66 67 /* 68 * Note that we must use "long" for underlying representations, 69 * because there is no compareAndSet for double, due to the fact 70 * that the bitwise equals used in any CAS implementation is not 71 * the same as double-precision equals. However, we use CAS only 72 * to detect and alleviate contention, for which bitwise equals 73 * works best anyway. In principle, the long/double conversions 74 * used here should be essentially free on most platforms since 75 * they just re-interpret bits. 76 */ 77 78 /** 79 * Creates a new adder with initial sum of zero. 80 */ 81 public DoubleAdder() { 82 } 83 84 /** 85 * Adds the given value. 86 * 87 * @param x the value to add 88 */ 89 public void add(double x) { 90 Cell[] cs; long b, v; int m; Cell c; 91 if ((cs = cells) != null || 92 !casBase(b = base, 93 Double.doubleToRawLongBits 94 (Double.longBitsToDouble(b) + x))) { 95 boolean uncontended = true; 96 if (cs == null || (m = cs.length - 1) < 0 || 97 (c = cs[getProbe() & m]) == null || 98 !(uncontended = c.cas(v = c.value, 99 Double.doubleToRawLongBits 100 (Double.longBitsToDouble(v) + x)))) 101 doubleAccumulate(x, null, uncontended); 102 } 103 } 104 105 /** 106 * Returns the current sum. The returned value is <em>NOT</em> an 107 * atomic snapshot; invocation in the absence of concurrent 108 * updates returns an accurate result, but concurrent updates that 109 * occur while the sum is being calculated might not be 110 * incorporated. Also, because floating-point arithmetic is not 111 * strictly associative, the returned result need not be identical 112 * to the value that would be obtained in a sequential series of 113 * updates to a single variable. 114 * 115 * @return the sum 116 */ 117 public double sum() { 118 Cell[] cs = cells; 119 double sum = Double.longBitsToDouble(base); 120 if (cs != null) { 121 for (Cell c : cs) 122 if (c != null) 123 sum += Double.longBitsToDouble(c.value); 124 } 125 return sum; 126 } 127 128 /** 129 * Resets variables maintaining the sum to zero. This method may 130 * be a useful alternative to creating a new adder, but is only 131 * effective if there are no concurrent updates. Because this 132 * method is intrinsically racy, it should only be used when it is 133 * known that no threads are concurrently updating. 134 */ 135 public void reset() { 136 Cell[] cs = cells; 137 base = 0L; // relies on fact that double 0 must have same rep as long 138 if (cs != null) { 139 for (Cell c : cs) 140 if (c != null) 141 c.reset(); 142 } 143 } 144 145 /** 146 * Equivalent in effect to {@link #sum} followed by {@link 147 * #reset}. This method may apply for example during quiescent 148 * points between multithreaded computations. If there are 149 * updates concurrent with this method, the returned value is 150 * <em>not</em> guaranteed to be the final value occurring before 151 * the reset. 152 * 153 * @return the sum 154 */ 155 public double sumThenReset() { 156 Cell[] cs = cells; 157 double sum = Double.longBitsToDouble(getAndSetBase(0L)); 158 if (cs != null) { 159 for (Cell c : cs) { 160 if (c != null) 161 sum += Double.longBitsToDouble(c.getAndSet(0L)); 162 } 163 } 164 return sum; 165 } 166 167 /** 168 * Returns the String representation of the {@link #sum}. 169 * @return the String representation of the {@link #sum} 170 */ 171 public String toString() { 172 return Double.toString(sum()); 173 } 174 175 /** 176 * Equivalent to {@link #sum}. 177 * 178 * @return the sum 179 */ 180 public double doubleValue() { 181 return sum(); 182 } 183 184 /** 185 * Returns the {@link #sum} as a {@code long} after a 186 * narrowing primitive conversion. 187 */ 188 public long longValue() { 189 return (long)sum(); 190 } 191 192 /** 193 * Returns the {@link #sum} as an {@code int} after a 194 * narrowing primitive conversion. 195 */ 196 public int intValue() { 197 return (int)sum(); 198 } 199 200 /** 201 * Returns the {@link #sum} as a {@code float} 202 * after a narrowing primitive conversion. 203 */ 204 public float floatValue() { 205 return (float)sum(); 206 } 207 208 /** 209 * Serialization proxy, used to avoid reference to the non-public 210 * Striped64 superclass in serialized forms. 211 * @serial include 212 */ 213 private static class SerializationProxy implements Serializable { 214 private static final long serialVersionUID = 7249069246863182397L; 215 216 /** 217 * The current value returned by sum(). 218 * @serial 219 */ 220 private final double value; 221 222 SerializationProxy(DoubleAdder a) { 223 value = a.sum(); 224 } 225 226 /** 227 * Returns a {@code DoubleAdder} object with initial state 228 * held by this proxy. 229 * 230 * @return a {@code DoubleAdder} object with initial state 231 * held by this proxy 232 */ 233 private Object readResolve() { 234 DoubleAdder a = new DoubleAdder(); 235 a.base = Double.doubleToRawLongBits(value); 236 return a; 237 } 238 } 239 240 /** 241 * Returns a 242 * <a href="{@docRoot}/serialized-form.html#java.util.concurrent.atomic.DoubleAdder.SerializationProxy"> 243 * SerializationProxy</a> 244 * representing the state of this instance. 245 * 246 * @return a {@link SerializationProxy} 247 * representing the state of this instance 248 */ 249 private Object writeReplace() { 250 return new SerializationProxy(this); 251 } 252 253 /** 254 * @param s the stream 255 * @throws java.io.InvalidObjectException always 256 */ 257 private void readObject(java.io.ObjectInputStream s) 258 throws java.io.InvalidObjectException { 259 throw new java.io.InvalidObjectException("Proxy required"); 260 } 261 262 }