Java Reference
In-Depth Information
Figure 16.2. Illustration of happens-before in the Java Memory Model.
16.1.4. Piggybacking on synchronization
Because of the strength of the happens-before ordering, you can sometimes piggyback on the
visibility properties of an existing synchronization. This entails combining the program or-
der rule for happens-before with one of the other ordering rules (usually the monitor lock or
volatile variable rule) to order accesses to a variable not otherwise guarded by a lock. This
technique is very sensitive to the order in which statements occur and is therefore quite fra-
gile; it is an advanced technique that should be reserved for squeezing the last drop of per-
formance out of the most performance-critical classes like ReentrantLock.
The implementation of the protected AbstractQueuedSynchronizer methods in Fu-
tureTask illustrates piggybacking. AQS maintains an integer of synchronizer state that Fu-
tureTask uses to store the task state: running, completed, or cancelled. But FutureTask also
maintains additional variables, such as the result of the computation. When one thread calls
set to save the result and another thread calls get to retrieve it, the two had better be ordered
Search WWH ::




Custom Search