AtomicReference getAndUpdate() method in Java with Examples
Last Updated :
15 Apr, 2021
The getAndUpdate() method of a AtomicReference class is used to atomically updates which updates the current value of the AtomicReference by applying the specified updateFunction operation on the current value. It takes an object of updateFunction interface as its parameter and applies the operation specified in the object to the current value. It returns the previous value.
Syntax:
public final V getAndUpdate(UnaryOperator<V> updateFunction)
Parameters: This method accepts updateFunction which is a side-effect-free function.
Return value: This method returns the previous value.
Below programs illustrate the getAndUpdate() method:
Program 1:
Java
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.UnaryOperator;
public class GFG {
public static void main(String args[])
{
AtomicReference<Integer> ref
= new AtomicReference<>( 987654 );
UnaryOperator twoDigits
= (v)
-> v.toString()
.substring( 0 , 2 );
int value = ref.getAndUpdate(twoDigits);
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.UnaryOperator;
public class GFG {
public static void main(String args[])
{
AtomicReference<String> ref
= new AtomicReference<>( "welcome" );
UnaryOperator twoDigits
= (v) -> v + " to gfg" ;
String value
= ref.getAndUpdate(twoDigits);
System.out.println(
"The AtomicReference previous value: "
+ value);
System.out.println(
"The AtomicReference new value: "
+ ref.get());
}
}
|
References: https://docs.oracle.com/javase/10/docs/api/java/util/concurrent/atomic/AtomicReference.html#getAndUpdate(java.util.function.UnaryOperator)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...