What is the LongAdder.increment() method in Java?

LongAdder can be used to consecutively add values to a number. LongAdder is thread-safe and internally maintains a set of variables to reduce contention over threads. As the number of updates (like add()) increases, LongAdder may result in higher memory consumption because the set of variables is held in the memory. When calling methods like sum (or equivalent result methods like sumAndReset or longValue), 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 0
LongAdder 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 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.

Free Resources