Example 11-2 Protecting a HashMap
public synchronized Object tweek(Object arg) {
Example 11-3 Subclassing an Unsafe Object
public class MyFoo extends Foo {
public synchronized Object frob(Object arg) {
return foo.super(arg);
When Should a Class Be Synchronized?
There is a tendency when writing a threaded program to declare all methods synchronized. This
would seem a good thing to do, as then they could all be safely called from any thread. But it's not.
The vast majority of objects that a program uses are called from code that already contains proper
protection. In our producer/ consumer examples, there was no need to make workpile.add()
and workpile.remove() synchronized because they were only called from producer and
Synchronized Collections in Java 2
In Java 2 several classes that previously had synchronized methods have gotten replacement
classes that don't [e.g., HashTable has synchronized methods, HashMap (new in Java 2) doesn't].
This is a good thing because HashMap runs faster. It is a good thing because it is fairly unlikely
that you need it to be synchronized anyway. But sometimes you do.
Java 2 has a clever method of dealing with this situation. Instead of making subclasses of the
various collection classes and synchronizing them, Java 2 provides a static factory method for
each collection class which will return a synchronized version of the collection. This is known to
design pattern folks as a decorator pattern.
So the idea is that you create a class, then call the factory method on it to get back a synchronized
version of that same class. Obviously, you must now use only the synchronized version of the
class. Each of the core collections has such a factory method:
Collection synchronizedCollection(Collection c)
Set synchronizedSet(Set c)
Map synchronizedMap(Map c)
List synchronizedList(List c)
SortedSet synchronizedSortedSet(SortedSet c)
SortedMap synchronizedSortedMap(SortedMap c)
So you use these methods to obtain synchronized collections (Code Example 11-4):
Example 11-4 Making Synchronized Collections
List syncdList = Collections.synchronizedList(list);
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks