Java Reference
In-Depth Information
If you are working with an interface instead of a class, you can provide
an alternate implementation that wraps the methods of the interface in
synchronized methods that forward the calls to another unsynchronized
object that implements the same interface. This will work with any im-
plementation of the interface, and is therefore a better solution than ex-
tending each class to use super in a synchronized method. This flexibility
is another reason to use interfaces to design your system. You can see
an example of this synchronized wrapper technique in the collections
classes; see " The Synchronized Wrappers " on page 602 .
The synchronization you have learned about so far is the simplest notion
of "thread safety"the idea that methods on objects can be invoked by
multiple threads concurrently and each thread will have the method per-
form its expected job. Synchronization, however, has to extend to more
complex situations involving multiple method invocations on an object,
or even method invocations on multiple objects. If these series of invoc-
ations must appear as an atomic action you will need synchronization. In
the case of multiple method invocations, you can encapsulate the series
of invocations within another method and synchronize that method, but
generally this is impracticalyou can't define all combinations of the basic
methods as methods themselves, nor are you likely to know at the time
the class is designed which method combinations may be needed. In the
case of operations on multiple objects, where could you put a synchron-
ized method?
In these situations, the ability to use client-side synchronization through
synchronized statements is often the only practical approach. An object
can have its lock acquired, which prevents any of its synchronized meth-
ods from being invoked except by the lock holder performing the series
of invocations. Similarly, you can acquire the locks of each of the ob-
jects involved and then invoke the series of methods on those objects-
but watch out for deadlock (see Section 14.7 on page 362 ). As long as
the object's methods are already synchronized on the current object's
lock, then other clients of the object need not use client-side synchron-
ization.
The way that synchronization is enforced in a class is an implementation
detail. The fact that it is enforced is an important part of the contract
of the class and must be clearly documentedthe presence of the syn-
 
Search WWH ::




Custom Search