Java Reference
In-Depth Information
Invoking synchronizedCollection(Collection c) returns a new Collection
object, in which all the methods that access and update the original collection c are synchro-
nized. These methods are implemented using the synchronized keyword. For example, the
add method is implemented like this:
public boolean add(E o) {
synchronized ( this ) {
return c.add(o);
}
}
Synchronized collections can be safely accessed and modified by multiple threads concurrently.
Note
The methods in java.util.Vector , java.util.Stack , and
java.util.Hashtable are already synchronized. These are old classes introduced
in JDK 1.0. Starting with JDK 1.5, you should use java.util.ArrayList to replace
Vector , java.util.LinkedList to replace Stack , and java.util.Map to
replace Hashtable . If synchronization is needed, use a synchronization wrapper.
The synchronization wrapper classes are thread-safe, but the iterator is fail-fast . This means
that if you are using an iterator to traverse a collection while the underlying collection is being
modified by another thread, then the iterator will immediately fail by throwing java.util.
ConcurrentModificationException , which is a subclass of RuntimeException . To
avoid this error, you need to create a synchronized collection object and acquire a lock on the
object when traversing it. For example, to traverse a set, you have to write the code like this:
fail-fast
Set hashSet = Collections.synchronizedSet( new HashSet());
synchronized (hashSet) { // Must synchronize it
Iterator iterator = hashSet.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
Failure to do so may result in nondeterministic behavior, such as a
ConcurrentModificationException .
30.35
What is a synchronized collection? Is ArrayList synchronized? How do you make
it synchronized?
Check
Point
30.36
Explain why an iterator is fail-fast.
30.16 Parallel Programming
The Fork/Join Framework is used for parallel programming in Java.
Key
Point
The widespread use of multicore systems has created a revolution in software. In order to
benefit from multiple processors, software needs to run in parallel. JDK 7 introduces the new
Fork/Join Framework for parallel programming, which utilizes the multicore processors.
The Fork/Join Framework is illustrated in Figure 30.27 (the diagram resembles a fork, hence
its name). A problem is divided into nonoverlapping subproblems, which can be solved indepen-
dently in parallel. The solutions to all subproblems are then joined to obtain an overall solution
for the problem. This is the parallel implementation of the divide-and-conquer approach. In JDK
7's Fork/Join Framework, a fork can be viewed as an independent task that runs on a thread.
JDK 7 feature
Fork/Join Framework
 
 
 
Search WWH ::




Custom Search