The Java.util.concurrent.atomic.AtomicLong.compareAndSet() is an inbuilt method in java that sets the value to the passed value in the parameter if the current value is equal to the expected value which is also passed in the parameter. The function returns a boolean value which gives us an idea if the update was done or not.
Syntax:
public final boolean compareAndSet(long expect,
long val)
Parameters: The function accepts two mandatory parameters which are described below:
- expect: specifies the value that the atomic object should be.
- val: specifies the value to be updated if the atomic integer is equal to expect.
Return value: The function returns a boolean value, it returns true on success else false.
Below programs illustrate the above method:
Program 1:
import java.util.concurrent.atomic.AtomicLong;
public class GFG {
public static void main(String args[])
{
AtomicLong val = new AtomicLong( 0 );
System.out.println( "Previous value: "
+ val);
boolean res = val.compareAndSet( 0 , 6 );
if (res)
System.out.println( "The value was "
+ "updated and it is "
+ val);
else
System.out.println( "The value was "
+ "not updated" );
}
}
|
Output:
Previous value: 0
The value was updated and it is 6
Program 2:
import java.util.concurrent.atomic.AtomicLong;
public class GFG {
public static void main(String args[])
{
AtomicLong val = new AtomicLong( 0 );
System.out.println( "Previous value: "
+ val);
boolean res = val.compareAndSet( 10 , 6 );
if (res)
System.out.println( "The value was "
+ "updated and it is "
+ val);
else
System.out.println( "The value was "
+ "not updated" );
}
}
|
Output:
Previous value: 0
The value was not updated
Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicLong.html#compareAndSet–
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 :
29 Jan, 2019
Like Article
Save Article