Java Reference
In-Depth Information
System.out.println(list.get(i));
}
}
public void run()
{
list.add(0, "Fuser1101");
}
public static void main(String[] args)
{
new ShowConcurrentFor().go();
}
}
This program uses the synchronizedList() method of the Collections utility class to
improve the thread safety of the code. The resulting list guarantees that methods that access
the list will execute entirely before another thread can access the list. This helps to prevent a
method in one thread from altering a collection while a method in another thread is traversing
the collection. To simulate a thread waking up at an inopportune time, the program launches a
new thread in the middle of a for loop.
Suppose that the first time you run this program, it prints:
Mixer1201
ShellAssembler1301
StarPress1401
StarPress1401
UnloadBuffer1501
CHALLENGE 28.4
[click
here]
Explain the output of the ShowConcurrentFor
program.
The program's behavior stems partially from the fact that it uses a for loop instead of using
an iterator and a while loop. The iterators that classes in the java.util package supply
provide fail-fast recognition of concurrent modification to a collection. If you modify the list
between calls to an iterator's next() method, the iterator will throw a Concurrent-
ModificationException .
Suppose that you modify the program to use an iterator instead of a for loop.
package com.oozinoz.applications;
import java.util.*;
public class ShowConcurrentIterator implements Runnable
{
private List list;
public static List upMachineNames()
{
Search WWH ::




Custom Search