WalzoneInterview Prep
πŸ“ž Interviewing soon? Practice with a realistic AI mock phone interview β€” it calls you, then scores you. First 15 min FREE β†’

Java Concurrency Β· Advanced Β· question 45 of 100

What is a CAS (Compare-and-Swap) operation and how is it used in Java?

πŸ“• Buy this interview preparation book: 100 Java Concurrency questions & answers β€” PDF + EPUB for $5

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.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Java Concurrency interview β€” then scores it.
πŸ“ž Practice Java Concurrency β€” free 15 min
πŸ“• Buy this interview preparation book: 100 Java Concurrency questions & answers β€” PDF + EPUB for $5

All 100 Java Concurrency questions Β· All topics