Java Reference
In-Depth Information
chronized modifier on a method might only be an implementation detail
of the class, not part of a binding contract. Additionally, the synchron-
ization mechanism used within a class may need to be documented and
made accessible to users of the class and/or to extended classes. An
extended class needs to adhere to the synchronization policy enforced
by its superclass and it can do that only if the programmer knows what
that policy is and has access to the mechanisms that enforce it. For ex-
ample, a class that uses a private field as a lock object prevents an ex-
tended class from using the same synchronization mechanismthe exten-
ded class would have to define its own lock object (perhaps this ) and
override every method of the superclass to use this new synchronization
mechanism. Users of a class may need to know what synchronization
mechanism is used so that they can safely apply client-side synchroniz-
ation to invoke multiple methods on an object, without needing all users
of that object to apply client-side synchronization.
Exercise 14.3 : Write a class whose objects hold a current value and
have a method that will add to that value, printing the new value. Write
a program that creates such an object, creates multiple threads, and in-
vokes the adding method repeatedly from each thread. Write the class
so that no addition can be lost.
Exercise 14.4 : Modify your code from Exercise 14.3 to use static data
and methods.
Exercise 14.5 : Modify your code from Exercise 14.4 so that threads can
safely decrement the value without using a static synchronized method.
 
Search WWH ::




Custom Search