The updateAndGet() 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 updated value.
Syntax:
public final V
updateAndGet(UnaryOperator<V> updateFunction)
Parameters: This method accepts updateFunction which is a side-effect-free function.
Return value: This method returns the updated value.
Below programs illustrate the updateAndGet() method:
Program 1:
import java.util.concurrent.atomic.*;
import java.util.function.UnaryOperator;
public class GFG {
public static void main(String args[])
{
AtomicReference<Integer> ref
= new AtomicReference<>( 987654 );
UnaryOperator function
= (v) -> Integer.parseInt(v.toString()) * 2 ;
int value = ref.updateAndGet(function);
System.out.println(
"The AtomicReference updated value: "
+ value);
}
}
|
Output:
Program 2:
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.updateAndGet(twoDigits);
System.out.println(
"The AtomicReference current value: "
+ value);
}
}
|
Output:
References: https://docs.oracle.com/javase/10/docs/api/java/util/concurrent/atomic/AtomicReference.html#updateAndGet(java.util.function.UnaryOperator)
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
03 Jan, 2020
Like Article
Save Article