LongAccumulator

Comprehensive guide to working with LongAccumulator.

If you are interviewing, consider buying our number#1 course for Java Multithreading Interviews.

Overview

The LongAccumulator class is similar to the LongAdder class, except that the LongAccumulator class allows for a function to be supplied that contains the logic for computing results for accumulation. In contrast to LongAdder, we can perform a variety of mathematical operations rather than just addition. The supplied function to a LongAccumulator is of type LongBinaryOperator. The class LongAccumulator extends from the class Number but doesn’t define the methods compareTo(), equals(), or hashCode() and shouldn’t be used as keys in collections such as maps.

An example of creating an accumulator that simply adds long values presented to it

// function that will be supplied to an instance of LongAccumulator
LongBinaryOperator longBinaryOperator = new LongBinaryOperator() {
   @Override
   public long applyAsLong(long left, long right) {
       return left + right;
   }
};

// instantiating an instance of LongAccumulator with an initial value of zero
LongAccumulator longAccumulator = new LongAccumulator(longBinaryOperator, 0);

Note that in the above example, we have supplied a function that simply adds the new long value presented to it. The method applyAsLong has two operands left and right. The left operand is the current value of the LongAccumulator. In the above example, it’ll be zero initially, because that is what we are passing-in to the constructor of the LongAccumulator instance. The code widget below runs this example and prints the operands and the final sum.

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy