Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Java Program to Implement CAS (Compare and Swap) Algorithm

  • Difficulty Level : Easy
  • Last Updated : 22 Feb, 2021

Compare and swap is a technique used when designing concurrent algorithms.  The approach is to compare the actual value of the variable to the expected value of the variable and if the actual value matches the expected value, then swap the actual value of the variable for the new value passed in.  

For understanding the algorithm, one must have the basic knowledge of Concurrency and Multithread in Java.

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

Working of the Algorithm:

It is like we know that this variable should be 1, and we want to change it to 2. Since this is a multithreaded environment, we know that others might be working on the same variable. So we should first check if the value of the variable is 1 as we thought and if yes, then we change it to 2. If we see that the variable is 3 now, then that means someone else is working on it and so let us not touch it at this time.



Check then Act approach:-

The most common condition for concurrency problems is the “check then act” approach. The “check then act”  occurs when the code first checks the value of a variable and then acts based on that value. Here is a simple example:

public boolean lock() {
    if(!locked) {
        lock = true;
        return true;
    }
    return false;
}

Above, pseudocode Implies that, if it is already locked, you don’t need to lock again. So you first check and only if required, act.

The above code is not safe as If two or more threads might have access to lock() function and do the check at the same time , then above lock() function would not be guaranteed to work because all thread would lock the resource and use it as it’s own. 

Let’s elaborate it : 

There is Thread A and Thread B, thread B may check locked at any time between thread A has checked locked and seen it to be false then, both thread A and thread B may see locked as being false, and both will then act based on that information.

The above problem can be resolved by making the entire block of code as synchronized. Then only one thread (thread A or thread B) going to the check and act at one time, Only after the thread that got into the code completes its check, and it’s an act then another thread gets to try. Now there will be no misunderstanding between threads.

Example for synchronized code :



class GFG {

    private boolean locked = false;

    public synchronized boolean lock() {
        if(!locked) {
            locked = true;
            return true;
        }
        return false;
    }
}

Now the lock() method is synchronized so only one thread can execute it at a time on the same lock() function. 

Atomic Operation

After Java 5, we don’t have to implement or write a synchronized block with the check and act code anymore, Java 5 offers this support via java.util.concurrent.atomic: a toolkit of classes used for lock-free, thread-safe programming on single variables. 

AtomicBoolean makes sure that only one thread can read it at a time.

Here is an example showing how to implement the lock() method using AtomicBoolean :

public static class MyLock {
    private AtomicBoolean locked = new AtomicBoolean(false);

    public boolean lock() {
        return locked.compareAndSet(false, true);
    }

}

Notice how the locked variable is no longer a boolean but an AtomicBoolean. This class has a compareAndSet() function which will compare the value of the AtomicBoolean instance to an expected value, and if has the expected value, it swaps the value with a new value. In this case it compares the value of locked to false and if it is false it sets the new value of the AtomicBoolean to true.

The compareAndSet() method returns true if the value was swapped, and false if not.

So there is many other Atomic Variable like:

  • AtomicInteger: This variable lets you update an int value atomically.
  • AtomicLong: Long with thread-safe “Compare and Swap” functionality.
  • AtomicReference: This variable provides an object reference variable which can be read and written atomically.
  • AtomicIntegerArray, AtomicLongArray, and AtomicReferenceArray

Example of Atomic Integer:

Java




// Java Program to demonstrates 
// the compareAndSet() function 
  
import java.util.concurrent.atomic.AtomicInteger; 
    
public class GFG { 
    public static void main(String args[]) 
    
    
        // Initially value as 0 
        AtomicInteger val = new AtomicInteger(0); 
    
        // Prints the updated value 
        System.out.println("Previous value: "
                           + val); 
    
        // Checks if previous value was 0 
        // and then updates it 
        boolean res = val.compareAndSet(0, 6); 
    
        // Checks if the value was updated. 
        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

When multiple threads attempt to update the same variable simultaneously using CAS(Compare and Swap) algorithm, one wins and updates the variable’s value, and the rest lose. But the losers are not punished by suspension of thread. They are free to retry the operation or simply do nothing.




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!