Java Reference
In-Depth Information
Listing 4.2. Using Confinement to Ensure Thread Safety.
This example makes no assumptions about the thread-safety of Person , but if it is mutable,
additional synchronization will be needed when accessing a Person retrieved from a Per-
sonSet . The most reliable way to do this would be to make Person thread-safe; less reli-
able would be to guard the Person objects with a lock and ensure that all clients follow the
protocol of acquiring the appropriate lock before accessing the Person .
Instance confinement is one of the easiest ways to build thread-safe classes. It also allows
flexibility in the choice of locking strategy; PersonSet happened to use its own intrinsic
lock to guard its state, but any lock, consistently used, would do just as well. Instance con-
finement also allows different state variables to be guarded by different locks. (For an ex-
ample of a class that uses multiple lock objects to guard its state, see ServerStatus on
236 . )
There are many examples of confinement in the platform class libraries, including some
classes that exist solely to turn non-thread-safe classes into threadsafe ones. The basic col-
lection classes such as ArrayList and HashMap are not thread-safe, but the class library
provides wrapper factory methods ( Collections.synchronizedList and friends) so
they can be used safely in multithreaded environments. These factories use the Decorator
pattern ( Gamma et al., 1995 ) to wrap the collection with a synchronized wrapper object; the
wrapper implements each method of the appropriate interface as a synchronized method that
Search WWH ::




Custom Search