What is the LongAdder.increment() method in Java?
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).
Syntax
public void increment()
This method doesn’t take any parameters and doesn’t return a value.
Code
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);}}
Explanation
In the code above, we:
-
Import the
LongAdderclass. -
Create a new object for
LongAdderwith the namenum. Initially, the value will be0. -
Use the
addmethod with6as an argument. -
Use the
incrementmethod on thenumobject and print the value ofnum. We will get7as our result.