Monday, July 29

What is compare and swap and compare and set (CAS)

What is compare and swap (CAS) and compare and set(CAS) in java?

In multithreaded java programming when a shared resource is accessed by multiple threads concurrently shared data needs to be synchronized for access and  visibility. But synchronization enforce locking and block all the threads but one trying to access the resource  This is optimistic approach of enforcing single access to shared resource at one time but it results huge degradation in multithreaded environment 

So there is one optimistic approach that is CAS - compare and swap

compare and swap?

What happens here is that a thread approach a shared resource with three variables 

a) current expected value
b) new value
c) memory address of the resource

So thread will access data from memory address will compare the current value with current expected value . If they match It will update the variable to new value. Obviously If multiple threads try making this operation simultaneously only one thread will succeed and others will fail. But other threads will not block instead invoker can continue with other operation or try the same again with failing threads. So this provides a lot better performance

and what is Compare and Set ?

Compare and Set is same as compare and swap . Only difference is that it returns a Boolean value as well which determines if operation succeeded or not. 

No comments:

Post a Comment