Java Reference
In-Depth Information
If extending a class to add another atomic operation is fragile because it distributes the lock-
ing code for a class over multiple classes in an object hierarchy, client-side locking is even
more fragile because it entails putting locking code for class
C
into classes that are totally
unrelated to
C
. Exercise care when using client-side locking on classes that do not commit to
their locking strategy.
Client-side locking has a lot in common with class extension—they both couple the behavior
of the derived class to the implementation of the base class. Just as extension violates encap-
sulation of implementation [EJ Item 14], client-side locking violates encapsulation of syn-
chronization policy.
4.4.2. Composition
There is a less fragile alternative for adding an atomic operation to an existing class:
com-
them to an underlying
List
instance, and adds an atomic
putIfAbsent
method. (Like
Collections.synchronizedList
and other collections wrappers,
ImprovedList
assumes that once a list is passed to its constructor, the client will not use the underlying list
directly again, accessing it only through the
ImprovedList
.)
Listing 4.16. Implementing Put-if-absent Using Composition.