Junior — Middle
Can you explain what CAS means and how it is used in programming?
sobes.tech AI
Answer from AI
CAS (Compare-And-Swap) is an atomic operation used in multithreaded programming to implement lock-free algorithms and synchronization.
The essence of CAS is that it compares the value in memory with an expected (old) value, and if they match, replaces it with a new value. All of this happens atomically, without interruptions.
This allows avoiding data races without using locks. For example, CAS is often used to implement atomic counters, lock-free queues, and other data structures.
In Java, CAS is implemented in the java.util.concurrent.atomic class through methods like compareAndSet.
Example of using AtomicInteger with CAS:
import java.util.concurrent.atomic.AtomicInteger;
AtomicInteger counter = new AtomicInteger(0);
boolean updated = counter.compareAndSet(0, 1); // if the current value is 0, set it to 1
If the value was 0, it changes to 1, and the method returns true; otherwise, it returns false.