Java Reference
In-Depth Information
The definition of thread safety requires that invariants be preserved regardless of timing or
interleaving of operations in multiple threads. One invariant of UnsafeCachingFact-
orizer is that the product of the factors cached in lastFactors equal the value cached
in lastNumber ; our servlet is correct only if this invariant always holds. When multiple
variables participate in an invariant, they are not independent : the value of one constrains the
allowed value(s) of the others. Thus when updating one, you must update the others in the
same atomic operation .
With some unlucky timing, UnsafeCachingFactorizer can violate this invariant.
Using atomic references, we cannot update both lastNumber and lastFactors simul-
taneously, even though each call to set is atomic; there is still a window of vulnerability
when one has been modified and the other has not, and during that time other threads could
see that the invariant does not hold. Similarly, the two values cannot be fetched simultan-
eously: between the time when thread A fetches the two values, thread B could have changed
them, and again A may observe that the invariant does not hold.
To preserve state consistency, update related state variables in a single atomic operation.
2.3.1. Intrinsic Locks
Java provides a built-in locking mechanism for enforcing atomicity: the synchronized
block. (There is also another critical aspect to locking and other synchronization mechan-
isms—visibility—which is covered in Chapter 3 .) A synchronized block has two parts:
a reference to an object that will serve as the lock , and a block of code to be guarded by that
lock. A synchronized method is a shorthand for a synchronized block that spans
an entire method body, and whose lock is the object on which the method is being invoked.
(Static synchronized methods use the Class object for the lock.)
Every Java object can implicitly act as a lock for purposes of synchronization; these built-in
locks are called intrinsic locks or monitor locks . The lock is automatically acquired by the
executing thread before entering a synchronized block and automatically released when
Search WWH ::




Custom Search