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