AtomicLong accumulateAndGet() method in Java with Examples

The Java.AtomicLong.accumulateAndGet() method is an inbuilt method, which updates the current value of the object by applying the specified operation on the current value and value passed as a parameter. It takes a long as its parameter and an object of LongBinaryOperator interface and applies the operation specified in the object to the values. It returns the updated value.

Syntax:

public final long accumulateAndGet(long y, 
              LongBinaryOperator function)

Parameters: This method accepts as parameter a long value y and an LongBinaryOperator function. It applies the given function to the current value of the object and the value y.



Return Value: The function returns the updated value of the current object.

Example to demonstrate the function.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java programt to demonstrate
// AtomicLong accumulateAndGet() method
  
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.LongBinaryOperator;
  
public class Demo {
    public static void main(String[] args)
    {
        // AtomicLong initialized with a value of 555
        AtomicLong atomicLong = new AtomicLong(555);
  
        // Binary operator defined
        // to calculate the product
        LongBinaryOperator binaryOperator
            = (x, y) -> x * y;
  
        System.out.println("Initial Value is "
                           + atomicLong);
  
        // Function called and the binary operator
        // is passed as an argument
        long value
            = atomicLong
                  .accumulateAndGet(555, binaryOperator);
        System.out.println("Updated value is "
                           + value);
    }
}

chevron_right


Output:

Initial Value is 555
Updated value is 308025

Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicLong.html



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.