Java Reference
In-Depth Information
VolatileCachedFactorizer in Listing 3.13 uses a OneValueCache to store the
cached number and factors. When a thread sets the volatile cache field to reference a new
OneValueCache , the new cached data becomes immediately visible to other threads.
The cache-related operations cannot interfere with each other because One-ValueCache
is immutable and the cache field is accessed only once in each of the relevant code paths.
This combination of an immutable holder object for multiple state variables related by
an invariant, and a volatile reference used to ensure its timely visibility, allows Volat-
ileCachedFactorizer to be thread-safe even though it does no explicit locking.
3.5. Safe Publication
So far we have focused on ensuring that an object not be published, such as when it is sup-
posed to be confined to a thread or within another object. Of course, sometimes we do want
to share objects across threads, and in this case we must do so safely. Unfortunately, simply
storing a reference to an object into a public field, as in Listing 3.14 , is not enough to publish
that object safely.
Search WWH ::




Custom Search