AtomicInteger getAndAccumulate() method in Java with Examples

The Java.AtomicInteger.getAndAccumulate() 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 an integer as its parameter and an object of IntBinaryOperator interface and applies the operation specified in the object to the values. It returns the previous value.

Syntax:

public final int getAndAccumulate(int y, 
                   IntBinaryOperator function)

Parameters: This method accepts two parameters:



  • y: an integer on which the function is to be applied.
  • function: function applied to the current value of the object and the value y.

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

Example to demonstrate the function.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// working of getAndAccumulate() method
  
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.IntBinaryOperator;
  
public class Demo {
    public static void main(String[] args)
    {
        new UserThread("Thread A");
        new UserThread("Thread B");
    }
}
  
class Shared {
    static AtomicInteger ai
        = new AtomicInteger(1);
}
  
class UserThread implements Runnable {
    String name;
  
    UserThread(String name)
    {
        this.name = name;
        new Thread(this).start();
    }
  
    IntBinaryOperator ibo = (x, y) -> (x * y);
  
    int value = 5;
    @Override
    public void run()
    {
        for (int i = 0; i < 3; i++) {
  
            int ans
                = Shared.ai
                      .getAndAccumulate(value, ibo);
  
            System.out.println(name + " "
                               + ans);
        }
    }
}

chevron_right


Output:

Thread A 1
Thread A 5
Thread A 25
Thread B 125
Thread B 625
Thread B 3125

Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.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.