Java Reference
In-Depth Information
3.1.3. Locking and Visibility
Intrinsic locking can be used to guarantee that one thread sees the effects of another in a pre-
dictable manner, as illustrated by Figure 3.1 . When thread A executes a synchronized
block, and subsequently thread B enters a synchronized block guarded by the same lock,
the values of variables that were visible to A prior to releasing the lock are guaranteed to be
visible to B upon acquiring the lock. In other words, everything A did in or prior to a syn-
chronized block is visible to B when it executes a synchronized block guarded by the
same lock. Without synchronization, there is no such guarantee.
Figure 3.1. Visibility Guarantees for Synchronization.
We can now give the other reason for the rule requiring all threads to synchronize on the
same lock when accessing a shared mutable variable—to guarantee that values written by
one thread are made visible to other threads. Otherwise, if a thread reads a variable without
holding the appropriate lock, it might see a stale value.
Search WWH ::




Custom Search