AtomicReferenceArray getAndUpdate() method in Java with Examples
Last Updated :
16 Apr, 2021
The getAndUpdate() method of a AtomicReferenceArray class is used to atomically updates which updates the current value of the AtomicReferenceArray 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 E
getAndUpdate(int i,
UnaryOperator<E> updateFunction)
Parameters: This method accepts:
- index i to update the index value and
- 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.*;
import java.util.function.UnaryOperator;
public class GFG {
public static void main(String args[])
{
String a[]
= { "GFG" , "JS" ,
"PYTHON" , "JAVA" };
AtomicReferenceArray<String> array
= new AtomicReferenceArray<>(a);
System.out.println(
"The AtomicReferenceArray before update : "
+ array);
int index = 2 ;
UnaryOperator add
= (u) -> u.toString() + " and ML" ;
String value
= array.getAndUpdate(index, add);
System.out.println( "previous value of index 2:"
+ value);
System.out.println( "The AtomicReferenceArray "
+ "after update: "
+ array);
}
}
|
Program 2:
Java
import java.util.concurrent.atomic.*;
import java.util.function.UnaryOperator;
public class GFG {
public static void main(String args[])
{
Integer a[] = { 213 , 1234 , 4543 , 345 };
AtomicReferenceArray<Integer> array
= new AtomicReferenceArray(a);
System.out.println(
"The AtomicReferenceArray"
+ " before update : "
+ array);
int index = 2 ;
UnaryOperator add
= (u) -> Integer.parseInt(u.toString()) * 200 ;
int value = array.getAndUpdate(index, add);
System.out.println( "previous value of index 2:"
+ value);
System.out.println( "updated value of index 2:"
+ array.get( 2 ));
System.out.println( "The AtomicReferenceArray "
+ "after update: "
+ array);
}
}
|
References: https://docs.oracle.com/javase/10/docs/api/java/util/concurrent/atomic/AtomicReferenceArray.html#getAndUpdate(java.util.function.UnaryOperator)
Share your thoughts in the comments
Please Login to comment...