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 0LongAdder 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
LongAdderclass. -
Line 7: We create a new object for
LongAdderwith the namenum. Initially, the value will be0. -
Line 8: We use the
addmethod, passing6as an argument. This will add the value6to the adder. -
Line 11: We use the
resetmethod on thenumobject. Theresetmethod will reset the variables maintaining the sum at0. Now the value ofnumis0.