What is a CAS Operation in Java ?

CAS is also known a Compare-And-Swap operation. In a CAS operation, the processor provides a separate instruction that can update the value of a register only if the provided value is equal to the current value.

CAS operation can be used as an alternate to synchronization.

Let say thread T1 can update a value by passing its current value and the new value to be updated to the CAS operation. In case another thread T2 has updated the current value of previous thread, the previous thread T1’s current value is not equal to the current value of T2. Hence the update operation fails.

In this case, thread T1 will read the current value again and try to update it.



You May Interest

What is the Difference Between a Set and a Map in Java ?

Why String Class is Immutable or Final in Java ?

How Stack and Heap Work in Java Multi-threading Environment ?

What are the Different States of a Thread in Java ?

What is Externalizable Interface in Java ?