Java Reference
In-Depth Information
with the update in the hope of success, and can detect failure if another thread has updated
the variable since it was last examined. SimulatedCAS in Listing 15.1 illustrates the se-
mantics (but not the implementation or performance) of CAS.
When multiple threads attempt to update the same variable simultaneously using CAS, one
wins and updates the variable's value, and the rest lose. But the losers are not punished by sus-
pension, as they could be if they failed to acquire a lock; instead, they are told that they didn't
win the race this time but can try again. Because a thread that loses a CAS is not blocked, it
can decide whether it wants to try again, take some other recovery action, or do nothing. [3]
This flexibility eliminates many of the liveness hazards associated with locking (though in
unusual cases can introduce the risk of livelock —see Section 10.3.3 ) .
Listing 15.1. Simulated CAS Operation.
The typical pattern for using CAS is first to read the value A from V , derive the new value B
from A , and then use CAS to atomically change V from A to B so long as no other thread has
changed V to another value in the meantime. CAS addresses the problem of implementing
Search WWH ::




Custom Search