Java AtomicInteger compareAndSet() method

The compareAndSet() method of Java AtomicInteger class compares the current value with the expected value. If both the values are same, it will update the value.

Syntax

Parameter

expect: It is the expected value

update: It is the new value

Return

This method returns the new value as an atomicInteger if the expected value is equal to the current value.

Example 1

Test it Now

Output:

the updated number: 444

Example 2

Test it Now

Output:

the updated number:222

In the above example, the expected value is not equal to the newValue so, the value is not updated and it remains as intial value.

Example 3

Test it Now

Output:

the updated number: 0

Example 4

Test it Now

Output:

the updated number: 100

Example 5

Test it Now

Output:

the updated number: -2





Latest Courses