Java Reference
In-Depth Information
Just as it is a good practice to make all fields private unless they need greater visibility
[EJ Item 12], it is a good practice to make all fields final unless they need to be mutable.
3.4.2. Example: Using Volatile to Publish Immutable Objects
In UnsafeCachingFactorizer on page 24 , we tried to use two AtomicReference s
to store the last number and last factors, but this was not thread-safe because we could not
fetch or update the two related values atomically. Using volatile variables for these values
would not be thread-safe for the same reason. However, immutable objects can sometimes
provide a weak form of atomicity.
The factoring servlet performs two operations that must be atomic: updating the cached result
and conditionally fetching the cached factors if the cached number matches the requested
number. Whenever a group of related data items must be acted on atomically, consider creat-
ing an immutable holder class for them, such as OneValueCache [14] in Listing 3.12 .
Race conditions in accessing or updating multiple related variables can be eliminated by us-
ing an immutable object to hold all the variables. With a mutable holder object, you would
have to use locking to ensure atomicity; with an immutable one, once a thread acquires a
reference to it, it need never worry about another thread modifying its state. If the variables
are to be updated, a new holder object is created, but any threads working with the previous
holder still see it in a consistent state.
Listing 3.12. Immutable Holder for Caching a Number and its Factors.
Search WWH ::




Custom Search