AtomicLongArray getAndSet() method in Java, examples
Original text: https://www . geeksforgeeks . org/atomicongarray-getandset-method-in-Java-with-examples/
Java . util . concurrent . atomic . AtomicLongArray . getandset() is a built-in method in Java that automatically sets a given value at any given position in an atomicongarray . This method takes as parameters the index value of the atomic clone array and the value to be set. It returns the value at the given index and then sets the new value at that index. The function getAndSet() is similar to the set() function, but the former returns a value while the latter does not.
Syntax:
Public final long getAndSet(int i, long newValue)
Parameters:This function accepts two parameters:
-
I–the index to be updated. newValue – The value to set at index i*
Return value:This function returns the value at the given index before updating The value is in Long.
The following program illustrates the above method:
Program 1:
“`java
// Java program that
// the getAndSet() functionimport demonstrates java.util.concurrent.atomic.AtomicLongArray;
public class GFG {
public static void main(String args[])
a
AtomicLongArray arr = new AtomicLongArray(a);// Displaying the AtomicLongArray
System.out.println(“The array : ” + arr);// Index where operation is performed
int idx = 0;// New value to set at idx
long val = 100;// Updating the value at
// idx applying getAndSet
. > System.out.println(“Value at index ” + idx
+ ” before the update is “
System.out. println(“The array after update : “
+ arr);“`java
The array : [11, 12, 13, 14, 15]
Value at index 0 before the update is 11
The array after update : [100, 12, 13 , 14, 15]“`
Program 2:
“`java
// Java program that
// the getAndSet() functionimport demonstrates java.util.concurrent.atomic.AtomicLongArray;
public class GFG {
public static void main(String args[])
a
AtomicLongArray arr = new AtomicLongArray(a);// Displaying the AtomicLongArray
System.out.println(“The array : ” + arr);// Index where operation is performed
int idx = 3;// New value to set at idx
long val = 10;// Updating the value at
// idx applying getAndSet
. > System.out.println(“Value at index ” + idx
+ ” before the update is “
System.out. println(“The array after update : “
+ arr);“`java
The array : [11, 12, 13, 14, 15]
Value at index 3 before the update is 14
The array after update : [11, 12, 13 , 10, 15]“`
Reference:
https://docs . Oracle . com/javase/8/docs/ API/Java/util/concurrent/atomic/atomicongarray . html # getAndSet-int-long-