Java Reference
In-Depth Information
atomic read-modify-write sequences without locking, because it can detect interference from
other threads.
15.2.2. A Nonblocking Counter
CasCounter in Listing 15.2 implements a thread-safe counter using CAS. The increment
operation follows the canonical form—fetch the old value, transform it to the new value
(adding one), and use CAS to set the new value. If the CAS fails, the operation is immediately
retried. Retrying repeatedly is usually a reasonable strategy, although in cases of extreme
contention it might be desirable to wait or back off before retrying to avoid livelock.
CasCounter does not block, though it may have to retry several [4] times if other threads
are updating the counter at the same time. (In practice, if all you need is a counter or sequence
generator, just use AtomicInteger or AtomicLong , which provide atomic increment
and other arithmetic methods.)
Listing 15.2. Nonblocking Counter Using CAS.
At first glance, the CAS-based counter looks as if it should perform worse than a lock-based
counter; it has more operations and a more complicated control flow, and depends on the
Search WWH ::




Custom Search