The CAS (Compare-and-Swap) operation is a concurrency primitive used in Java to implement lock-free algorithms. It is an atomic operation that reads the current value of a memory location, compares it to an expected value, and if they are equal, replaces the old value with a new value.
The CAS operation is often used in multi-threaded environments where multiple threads can attempt to update the same variable concurrently. Instead of using locks or other synchronization mechanisms, CAS provides a way for threads to update the variable atomically without blocking or waiting for other threads to release the lock.
In Java, the CAS operation is provided by the java.util.concurrent.atomic package, which contains classes such as AtomicInteger, AtomicLong, and AtomicReference that use CAS internally to provide thread-safe operations.
Here is an example of using CAS to increment an integer value atomically:
import java.util.concurrent.atomic.AtomicInteger;
public class CasExample {
private static AtomicInteger counter = new AtomicInteger(0);
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread(() -> {
int oldValue, newValue;
do {
oldValue = counter.get();
newValue = oldValue + 1;
} while (!counter.compareAndSet(oldValue, newValue));
}).start();
}
System.out.println(counter.get()); // expected output: 10
}
}
In this example, we create a shared AtomicInteger object called counter and start 10 threads that each attempt to increment its value. The compareAndSet method is used to perform the CAS operation, where the current value of the counter is compared to the expected value (the oldValue), and if they match, the new value (the newValue) is set.
Itβs important to note that the CAS operation can fail if another thread updates the value in between the time when the oldValue is read and the compareAndSet operation is performed. To handle this situation, the operation is repeated in a loop until it succeeds, as shown in the example code above.