Java Reference
In-Depth Information
need to use your own experience and judgment to decide when this is
preferable. For example, in the Body class we could encapsulate access
to nextID in a static synchronized method getNextID .
Finally, the ability to acquire locks of arbitrary objects with synchronized
statements makes it possible to perform the client-side synchronization
that you saw in the array example. This capability is important, not only
for protecting access to objects that don't have synchronized methods,
but also for synchronizing a series of accesses to an object. We look
more at this in the next section.
14.3.4. Synchronization Designs
Designing the appropriate synchronization for a class can be a complex
matter and it is beyond the scope of this topic to delve too deeply into
these design issues. We can take a brief look at some of the issues in-
volved.
Client-side synchronization is done by having all the clients of a shared
object use synchronized statements to lock the object before using it.
Such a protocol is fragileit relies on all of the clients doing the right
thing. It is generally better to have shared objects protect access to
themselves by making their methods synchronized (or using appropriate
synchronized statements inside those methods). This makes it impossible
for a client to use the object in a way that is not synchronized. This ap-
proach is sometimes termed server-side synchronization, but it is just
an extension of the object-oriented perspective that objects encapsulate
their own behavior, in this case synchronization.
Sometimes a designer hasn't considered a multithreaded environment
when designing a class, and none of the class's methods are synchron-
ized. To use such a class in a multithreaded environment, you have to
decide whether to use client-side synchronization via synchronized state-
ments or to create an extended class to override the appropriate meth-
ods, declare them synchronized , and forward method calls through the
super reference.
 
Search WWH ::




Custom Search