Java Reference
In-Depth Information
forwards the request to the underlying collection object. So long as the wrapper object holds
the only reachable reference to the underlying collection (i.e., the underlying collection is
confined to the wrapper), the wrapper object is then thread-safe. The Javadoc for these meth-
ods warns that all access to the underlying collection must be made through the wrapper.
Of course, it is still possible to violate confinement by publishing a supposedly confined ob-
ject; if an object is intended to be confined to a specific scope, then letting it escape from that
scope is a bug. Confined objects can also escape by publishing other objects such as iterators
or inner class instances that may indirectly publish the confined objects.
Confinement makes it easier to build thread-safe classes because a class that confines its state
can be analyzed for thread safety without having to examine the whole program.
4.2.1. The Java Monitor Pattern
Following the principle of instance confinement to its logical conclusion leads you to the
Java monitor pattern . [2] An object following the Java monitor pattern encapsulates all its
mutable state and guards it with the object's own intrinsic lock.
Counter in Listing 4.1 shows a typical example of this pattern. It encapsulates one state
variable, value , and all access to that state variable is through the methods of Counter ,
which are all synchronized.
The Java monitor pattern is used by many library classes, such as Vector and Hashtable .
Sometimes a more sophisticated synchronization policy is needed; Chapter 11 shows how to
improve scalability through finer-grained locking strategies. The primary advantage of the
Java monitor pattern is its simplicity.
The Java monitor pattern is merely a convention; any lock object could be used to guard an
object's state so long as it is used consistently. Listing 4.3 illustrates a class that uses a private
lock to guard its state.
Listing 4.3. Guarding State with a Private Lock.
Search WWH ::




Custom Search