Java Reference
In-Depth Information
Extension is more fragile than adding code directly to a class, because the implementation
of the synchronization policy is now distributed over multiple, separately maintained source
files. If the underlying class were to change its synchronization policy by choosing a different
lock to guard its state variables, the subclass would subtly and silently break, because it no
longer used the right lock to control concurrent access to the base class's state. (The syn-
chronization policy of
Vector
is fixed by its specification, so
BetterVector
would not
suffer from this problem.)
Listing 4.13. Extending
Vector
to have a Put-if-absent Method.
4.4.1. Client-side Locking
For an
ArrayList
wrapped with a
Collections.synchronizedList
wrapper,
neither of these approaches—adding a method to the original class or extending the
class—works because the client code does not even know the class of the
List
object re-
turned from the synchronized wrapper factories. A third strategy is to extend the functionality
of the class without extending the class itself by placing extension code in a “helper” class.
Listing 4.14
shows a failed attempt to create a helper class with an atomic put-if-absent oper-
ation for operating on a thread-safe
List
.
Listing 4.14. Non-thread-safe Attempt to Implement Put-if-absent.
Don't do this.