What is LongAdder.reset() method in Java?

The LongAdder can be used to add values to a number consecutively.

The LongAdder is thread-safe. It maintains a set of variables internally to reduce contention over threads.

As the number of updates (like add()) increases, the LongAdder may result in higher memory consumption due to the set of variables held in the memory. On calling the methods like sum (or methods of equivalent result, like sumAndReset, longValue) the actual value is returned by combining the values of the set of variables.

The reset method resets variables so that the sum is maintained at zero.

This method should be called only when no threads are concurrently updating.

This method can also be used as an alternative for creating a new LongAdder object.

Syntax

public void reset()

This method doesn’t take any argument and doesn’t return any value.

Code

The code below demonstrates how to use the reset method:

import java.util.concurrent.atomic.LongAdder;
class Reset {
public static void main(String args[]) {
// Initialized with 0
LongAdder num = new LongAdder();
num.add(6);
System.out.println("After num.add(6): " + num);
num.reset();
System.out.println("After num.reset(): " + num);
}
}

Explanation

In the code above,

  • Line 1: We import the LongAdder class.

  • Line 7: We create a new object for LongAdder with the name num. Initially, the value will be 0.

  • Line 8: We use the add method, passing 6 as an argument. This will add the value 6 to the adder.

  • Line 11: We use the reset method on the num object. The reset method will reset the variables maintaining the sum at 0. Now the value of num is 0.

Free Resources