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 import java.io.Serializable; 38 import java.util.function.DoubleBinaryOperator; 39 40 /** 41 * One or more variables that together maintain a running {@code double} 42 * value updated using a supplied function. When updates (method 43 * {@link #accumulate}) are contended across threads, the set of variables 44 * may grow dynamically to reduce contention. Method {@link #get} 45 * (or, equivalently, {@link #doubleValue}) returns the current value 46 * across the variables maintaining updates. 47 * 48 * <p>This class is usually preferable to alternatives when multiple 49 * threads update a common value that is used for purposes such as 50 * summary statistics that are frequently updated but less frequently 51 * read. 52 * 53 * <p>The supplied accumulator function should be side-effect-free, 54 * since it may be re-applied when attempted updates fail due to 55 * contention among threads. The function is applied with the current 56 * value as its first argument, and the given update as the second 57 * argument. For example, to maintain a running maximum value, you 58 * could supply {@code Double::max} along with {@code 59 * Double.NEGATIVE_INFINITY} as the identity. The order of 60 * accumulation within or across threads is not guaranteed. Thus, this 61 * class may not be applicable if numerical stability is required, 62 * especially when combining values of substantially different orders 63 * of magnitude. 64 * 65 * <p>Class {@link DoubleAdder} provides analogs of the functionality 66 * of this class for the common special case of maintaining sums. The 67 * call {@code new DoubleAdder()} is equivalent to {@code new 68 * DoubleAccumulator((x, y) -> x + y, 0.0}. 69 * 70 * <p>This class extends {@link Number}, but does <em>not</em> define 71 * methods such as {@code equals}, {@code hashCode} and {@code 72 * compareTo} because instances are expected to be mutated, and so are 73 * not useful as collection keys. 74 * 75 * @since 1.8 76 * @author Doug Lea 77 */ 78 public class DoubleAccumulator extends Striped64 implements Serializable { 79 private static final long serialVersionUID = 7249069246863182397L; 80 81 private final DoubleBinaryOperator function; 82 private final long identity; // use long representation 83 84 /** 85 * Creates a new instance using the given accumulator function 86 * and identity element. 87 */ 88 public DoubleAccumulator(DoubleBinaryOperator accumulatorFunction, 89 double identity) { 90 this.function = accumulatorFunction; 91 base = this.identity = Double.doubleToRawLongBits(identity); 92 } 93 94 /** 95 * Updates with the given value. 96 * 97 * @param x the value 98 */ 99 public void accumulate(double x) { 100 Cell[] as; long b, v, r; int m; Cell a; 101 if ((as = cells) != null || 102 (r = Double.doubleToRawLongBits 103 (function.operateAsDouble 104 (Double.longBitsToDouble(b = base), x))) != b && !casBase(b, r)) { 105 boolean uncontended = true; 106 if (as == null || (m = as.length - 1) < 0 || 107 (a = as[getProbe() & m]) == null || 108 !(uncontended = 109 (r = Double.doubleToRawLongBits 110 (function.operateAsDouble 111 (Double.longBitsToDouble(v = a.value), x))) == v || 112 a.cas(v, r))) 113 doubleAccumulate(x, function, uncontended); 114 } 115 } 116 117 /** 118 * Returns the current value. The returned value is <em>NOT</em> 119 * an atomic snapshot; invocation in the absence of concurrent 120 * updates returns an accurate result, but concurrent updates that 121 * occur while the value is being calculated might not be 122 * incorporated. 123 * 124 * @return the current value 125 */ 126 public double get() { 127 Cell[] as = cells; Cell a; 128 double result = Double.longBitsToDouble(base); 129 if (as != null) { 130 for (int i = 0; i < as.length; ++i) { 131 if ((a = as[i]) != null) 132 result = function.operateAsDouble 133 (result, Double.longBitsToDouble(a.value)); 134 } 135 } 136 return result; 137 } 138 139 /** 140 * Resets variables maintaining updates to the identity value. 141 * This method may be a useful alternative to creating a new 142 * updater, but is only effective if there are no concurrent 143 * updates. Because this method is intrinsically racy, it should 144 * only be used when it is known that no threads are concurrently 145 * updating. 146 */ 147 public void reset() { 148 Cell[] as = cells; Cell a; 149 base = identity; 150 if (as != null) { 151 for (int i = 0; i < as.length; ++i) { 152 if ((a = as[i]) != null) 153 a.value = identity; 154 } 155 } 156 } 157 158 /** 159 * Equivalent in effect to {@link #get} followed by {@link 160 * #reset}. This method may apply for example during quiescent 161 * points between multithreaded computations. If there are 162 * updates concurrent with this method, the returned value is 163 * <em>not</em> guaranteed to be the final value occurring before 164 * the reset. 165 * 166 * @return the value before reset 167 */ 168 public double getThenReset() { 169 Cell[] as = cells; Cell a; 170 double result = Double.longBitsToDouble(base); 171 base = identity; 172 if (as != null) { 173 for (int i = 0; i < as.length; ++i) { 174 if ((a = as[i]) != null) { 175 double v = Double.longBitsToDouble(a.value); 176 a.value = identity; 177 result = function.operateAsDouble(result, v); 178 } 179 } 180 } 181 return result; 182 } 183 184 /** 185 * Returns the String representation of the current value. 186 * @return the String representation of the current value 187 */ 188 public String toString() { 189 return Double.toString(get()); 190 } 191 192 /** 193 * Equivalent to {@link #get}. 194 * 195 * @return the current value 196 */ 197 public double doubleValue() { 198 return get(); 199 } 200 201 /** 202 * Returns the {@linkplain #get current value} as a {@code long} 203 * after a narrowing primitive conversion. 204 */ 205 public long longValue() { 206 return (long)get(); 207 } 208 209 /** 210 * Returns the {@linkplain #get current value} as an {@code int} 211 * after a narrowing primitive conversion. 212 */ 213 public int intValue() { 214 return (int)get(); 215 } 216 217 /** 218 * Returns the {@linkplain #get current value} as a {@code float} 219 * after a narrowing primitive conversion. 220 */ 221 public float floatValue() { 222 return (float)get(); 223 } 224 225 private void writeObject(java.io.ObjectOutputStream s) 226 throws java.io.IOException { 227 s.defaultWriteObject(); 228 s.writeDouble(get()); 229 } 230 231 private void readObject(java.io.ObjectInputStream s) 232 throws java.io.IOException, ClassNotFoundException { 233 s.defaultReadObject(); 234 cellsBusy = 0; 235 cells = null; 236 base = Double.doubleToRawLongBits(s.readDouble()); 237 } 238 239 }