NOTE

6.4 CAS

1. What it is. To understand CAS, first understand optimistic and pessimistic locking. 1.1. Optimistic vs. pessimistic locking. 1.2. CAS. 2. How to use it.

JavaCreated Updated 1 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. What It Is

To understand CAS, we first need to understand the concepts of optimistic locking and pessimistic locking.

1.1. Optimistic Locking vs. Pessimistic Locking

Pessimistic locking: assume that whenever data is being operated on, someone else will operate on the same data at the same time. Therefore, I lock the data before operating on it. Until I finish and release the lock, everyone else can only block and wait.

Optimistic locking: assume that whenever data is being operated on, nobody else will operate on it at the same time. Therefore, only when updating do I check whether someone else has modified the data. If so, retry until the update succeeds.

1.2. CAS

CAS is one form of optimistic locking. Java’s AQS and AtomicXXX classes are all implemented based on CAS.

CAS stands for compare and set: compare and set the value of a variable. It is an atomic operation.

Take CAS(A, B) as an example. Three values are involved: the actual value A1 in memory, the currently read value A (also called the expected value), and the new value B. If and only if A1 == A, the value is changed to B.

2. How to Use It

The implementations of the Atomic classes in the JUC package use CAS. See Atomic.md.

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub