Java Reference
In-Depth Information
Listing 15.5. Random Number Generator Using AtomicInteger .
As these graphs show, at high contention levels locking tends to outperform atomic variables,
but at more realistic contention levels atomic variables outperform locks. [6] This is because
a lock reacts to contention by suspending threads, reducing CPU usage and synchronization
traffic on the shared memory bus. (This is similar to how blocking producers in a producer-
consumer design reduces the load on consumers and thereby lets them catch up.) On the other
hand, with atomic variables, contention management is pushed back to the calling class. Like
most CAS-based algorithms, AtomicPseudoRandom reacts to contention by trying again
immediately, which is usually the right approach but in a high-contention environment just
creates more contention.
Before we condemn AtomicPseudoRandom as poorly written or atomic variables as a
poor choice compared to locks, we should realize that the level of contention in Figure 15.1 is
unrealistically high: no real program does nothing but contend for a lock or atomic variable.
In practice, atomics tend to scale better than locks because atomics deal more effectively with
typical contention levels.
Search WWH ::




Custom Search