LongAddercan be used to consecutively add values to a number.LongAdderis thread-safe and internally maintains a set of variables to reduce contention over threads. As the number of updates (likeadd()) increases,LongAddermay result in higher memory consumption because the set of variables is held in the memory. When calling methods likesum(or equivalent result methods likesumAndResetorlongValue), the actual value is returned by combining the values of the set of variables.
The increment method can be used to increase the value by 1.
The increment method is equivalent to add(1).
public void increment()
This method doesn’t take any parameters and doesn’t return a value.
The code below demonstrates how to use the increment method.
import java.util.concurrent.atomic.LongAdder;class Increment {public static void main(String args[]) {// Initialized with 0LongAdder num = new LongAdder();num.add(6);System.out.println("After num.add(6): " + num);num.increment();System.out.println("After num.increment(): " + num);}}
In the code above, we:
Import the LongAdder class.
Create a new object for LongAdder with the name num. Initially, the value will be 0.
Use the add method with 6 as an argument.
Use the increment method on the num object and print the value of num. We will get 7 as our result.