AtomicReference getAndAccumulate() method in Java with Examples
Last Updated :
15 Apr, 2021
The getAndAccumulate() method of a AtomicReference class is used to atomically updates the current value of AtomicReference with the results of applying the given accumulatorFunction to the current and given values and returns the previous value. The accumulatorFunction should be side-effect-free, since it may be re-applied when attempted updates fail due to contention among threads. The function is applied with the current value as its first argument, and the given update as the second argument.
Syntax:
public final E getAndAccumulate(E x,
BinaryOperator<E> accumulatorFunction)
Parameters: This method accepts:
- x which is the updated value and
- accumulatorFunction which is a side-effect-free function of two arguments.
Return value: This method returns the previous value.
Below programs illustrate the getAndAccumulate() method:
Program 1:
Java
import java.util.concurrent.atomic.*;
import java.util.function.BinaryOperator;
public class GFG {
public static void main(String args[])
{
AtomicReference<Integer> ref
= new AtomicReference<>( 3456 );
int x = 45654 ;
BinaryOperator add
= (u, v) -> u.toString() + v.toString();
int value = ref.getAndAccumulate(x, add);
System.out.println(
"The AtomicReference previous value: "
+ value);
System.out.println(
"The AtomicReference new value: "
+ ref.get());
}
}
|
Program 2:
Java
import java.util.concurrent.atomic.*;
import java.util.function.BinaryOperator;
public class GFG {
public static void main(String args[])
{
AtomicReference<String> ref
= new AtomicReference<String>( "GFG " );
String x = "Welcome" ;
BinaryOperator add
= (u, v) -> v + " to " + u;
String previousValue
= ref.getAndAccumulate(x, add);
System.out.println(
"The AtomicReference previous value: "
+ previousValue);
}
}
|
References: https://docs.oracle.com/javase/10/docs/api/java/util/concurrent/atomic/AtomicReference.html#getAndAccumulate(V, java.util.function.BinaryOperator)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...