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 import java.util.function.LongBinaryOperator;
  40 
  41 /**
  42  * One or more variables that together maintain a running {@code long}
  43  * value updated using a supplied function.  When updates (method
  44  * {@link #accumulate}) are contended across threads, the set of variables
  45  * may grow dynamically to reduce contention.  Method {@link #get}
  46  * (or, equivalently, {@link #longValue}) returns the current value
  47  * across the variables maintaining updates.
  48  *
  49  * <p>This class is usually preferable to {@link AtomicLong} when
  50  * multiple threads update a common value that is used for purposes such
  51  * as collecting statistics, not for fine-grained synchronization
  52  * control.  Under low update contention, the two classes have similar
  53  * characteristics. But under high contention, expected throughput of
  54  * this class is significantly higher, at the expense of higher space
  55  * consumption.
  56  *
  57  * <p>The order of accumulation within or across threads is not
  58  * guaranteed and cannot be depended upon, so this class is only
  59  * applicable to functions for which the order of accumulation does
  60  * not matter. The supplied accumulator function should be
  61  * side-effect-free, since it may be re-applied when attempted updates
  62  * fail due to contention among threads. For predictable results, the
  63  * accumulator function should be associative and commutative. The
  64  * function is applied with an existing value (or identity) as one
  65  * argument, and a given update as the other argument.  For example,
  66  * to maintain a running maximum value, you could supply {@code
  67  * Long::max} along with {@code Long.MIN_VALUE} as the identity.
  68  *
  69  * <p>Class {@link LongAdder} provides analogs of the functionality of
  70  * this class for the common special case of maintaining counts and
  71  * sums.  The call {@code new LongAdder()} is equivalent to {@code new
  72  * LongAccumulator((x, y) -> x + y, 0L)}.
  73  *
  74  * <p>This class extends {@link Number}, but does <em>not</em> define
  75  * methods such as {@code equals}, {@code hashCode} and {@code
  76  * compareTo} because instances are expected to be mutated, and so are
  77  * not useful as collection keys.
  78  *
  79  * @since 1.8
  80  * @author Doug Lea
  81  */
  82 public class LongAccumulator extends Striped64 implements Serializable {
  83     private static final long serialVersionUID = 7249069246863182397L;
  84 
  85     private final LongBinaryOperator function;
  86     private final long identity;
  87 
  88     /**
  89      * Creates a new instance using the given accumulator function
  90      * and identity element.
  91      * @param accumulatorFunction a side-effect-free function of two arguments
  92      * @param identity identity (initial value) for the accumulator function
  93      */
  94     public LongAccumulator(LongBinaryOperator accumulatorFunction,
  95                            long identity) {
  96         this.function = accumulatorFunction;
  97         base = this.identity = identity;
  98     }
  99 
 100     /**
 101      * Updates with the given value.
 102      *
 103      * @param x the value
 104      */
 105     public void accumulate(long x) {
 106         Cell[] cs; long b, v, r; int m; Cell c;
 107         if ((cs = cells) != null
 108             || ((r = function.applyAsLong(b = base, x)) != b
 109                 && !casBase(b, r))) {
 110             boolean uncontended = true;
 111             if (cs == null
 112                 || (m = cs.length - 1) < 0
 113                 || (c = cs[getProbe() & m]) == null
 114                 || !(uncontended =
 115                      (r = function.applyAsLong(v = c.value, x)) == v
 116                      || c.cas(v, r)))
 117                 longAccumulate(x, function, uncontended);
 118         }
 119     }
 120 
 121     /**
 122      * Returns the current value.  The returned value is <em>NOT</em>
 123      * an atomic snapshot; invocation in the absence of concurrent
 124      * updates returns an accurate result, but concurrent updates that
 125      * occur while the value is being calculated might not be
 126      * incorporated.
 127      *
 128      * @return the current value
 129      */
 130     public long get() {
 131         Cell[] cs = cells;
 132         long result = base;
 133         if (cs != null) {
 134             for (Cell c : cs)
 135                 if (c != null)
 136                     result = function.applyAsLong(result, c.value);
 137         }
 138         return result;
 139     }
 140 
 141     /**
 142      * Resets variables maintaining updates to the identity value.
 143      * This method may be a useful alternative to creating a new
 144      * updater, but is only effective if there are no concurrent
 145      * updates.  Because this method is intrinsically racy, it should
 146      * only be used when it is known that no threads are concurrently
 147      * updating.
 148      */
 149     public void reset() {
 150         Cell[] cs = cells;
 151         base = identity;
 152         if (cs != null) {
 153             for (Cell c : cs)
 154                 if (c != null)
 155                     c.reset(identity);
 156         }
 157     }
 158 
 159     /**
 160      * Equivalent in effect to {@link #get} followed by {@link
 161      * #reset}. This method may apply for example during quiescent
 162      * points between multithreaded computations.  If there are
 163      * updates concurrent with this method, the returned value is
 164      * <em>not</em> guaranteed to be the final value occurring before
 165      * the reset.
 166      *
 167      * @return the value before reset
 168      */
 169     public long getThenReset() {
 170         Cell[] cs = cells;
 171         long result = getAndSetBase(identity);
 172         if (cs != null) {
 173             for (Cell c : cs) {
 174                 if (c != null) {
 175                     long v = c.getAndSet(identity);
 176                     result = function.applyAsLong(result, v);
 177                 }
 178             }
 179         }
 180         return result;
 181     }
 182 
 183     /**
 184      * Returns the String representation of the current value.
 185      * @return the String representation of the current value
 186      */
 187     public String toString() {
 188         return Long.toString(get());
 189     }
 190 
 191     /**
 192      * Equivalent to {@link #get}.
 193      *
 194      * @return the current value
 195      */
 196     public long longValue() {
 197         return get();
 198     }
 199 
 200     /**
 201      * Returns the {@linkplain #get current value} as an {@code int}
 202      * after a narrowing primitive conversion.
 203      */
 204     public int intValue() {
 205         return (int)get();
 206     }
 207 
 208     /**
 209      * Returns the {@linkplain #get current value} as a {@code float}
 210      * after a widening primitive conversion.
 211      */
 212     public float floatValue() {
 213         return (float)get();
 214     }
 215 
 216     /**
 217      * Returns the {@linkplain #get current value} as a {@code double}
 218      * after a widening primitive conversion.
 219      */
 220     public double doubleValue() {
 221         return (double)get();
 222     }
 223 
 224     /**
 225      * Serialization proxy, used to avoid reference to the non-public
 226      * Striped64 superclass in serialized forms.
 227      * @serial include
 228      */
 229     private static class SerializationProxy implements Serializable {
 230         private static final long serialVersionUID = 7249069246863182397L;
 231 
 232         /**
 233          * The current value returned by get().
 234          * @serial
 235          */
 236         private final long value;
 237 
 238         /**
 239          * The function used for updates.
 240          * @serial
 241          */
 242         private final LongBinaryOperator function;
 243 
 244         /**
 245          * The identity value.
 246          * @serial
 247          */
 248         private final long identity;
 249 
 250         SerializationProxy(long value,
 251                            LongBinaryOperator function,
 252                            long identity) {
 253             this.value = value;
 254             this.function = function;
 255             this.identity = identity;
 256         }
 257 
 258         /**
 259          * Returns a {@code LongAccumulator} object with initial state
 260          * held by this proxy.
 261          *
 262          * @return a {@code LongAccumulator} object with initial state
 263          * held by this proxy
 264          */
 265         private Object readResolve() {
 266             LongAccumulator a = new LongAccumulator(function, identity);
 267             a.base = value;
 268             return a;
 269         }
 270     }
 271 
 272     /**
 273      * Returns a
 274      * <a href="../../../../serialized-form.html#java.util.concurrent.atomic.LongAccumulator.SerializationProxy">
 275      * SerializationProxy</a>
 276      * representing the state of this instance.
 277      *
 278      * @return a {@link SerializationProxy}
 279      * representing the state of this instance
 280      */
 281     private Object writeReplace() {
 282         return new SerializationProxy(get(), function, identity);
 283     }
 284 
 285     /**
 286      * @param s the stream
 287      * @throws java.io.InvalidObjectException always
 288      */
 289     private void readObject(java.io.ObjectInputStream s)
 290         throws java.io.InvalidObjectException {
 291         throw new java.io.InvalidObjectException("Proxy required");
 292     }
 293 
 294 }