Written by - Yash Agrawal

memcached cas command


CAS Check and set sometimes also known as Compare and Swap. This command is used to set data if it is not updated since last fetch. In simpler words CAS means to only store data when no oine else has updated the data since the last read. This command is very useful for resolving race conditions on updating cache data.

Code Example:
set key flags exptime bytes unique_cas_key [noreply] 
value

Here Unique_cas_key means this is the unique key and get from the gets command.

The program will return four types of output. STORED , ERROR, EXISTS, NOT_FOUND.

Java Code Example:

import net.spy.memcached.MemcachedClient;  
public class MemcachedJava {  
   public static void main(String[] args) {  
       
     // Connecting to Memcached server on localhost  
      MemcachedClient mcc = new MemcachedClient(new  
      InetSocketAddress("127.0.0.1", 11211));  
      System.out.println("Connection to server successful");  
      System.out.println("set status:"+mcc.set("nm", 900, "amandeep").isDone());  
  
      // Get cas token from cache  
      long castToken = mcc.gets("nm").cas;  
      System.out.println("Cas token:"+castToken);  
  
      // now set new data in memcached server  
      System.out.println("Now set new data:"+mcc.cas("nm",  
      castToken, 900, "deep"));  
      System.out.println("Get from Cache:"+mcc.get("nm"));  
   }  
}