Java Reference
In-Depth Information
SOLUTION 28.5
To make a clone of a collection before iterating over it, you have to ensure that the source
collection is cloneable. Create a synchronized version of the collection for general access, and
synchronize on this collection when cloning the underlying source collection:
package com.oozinoz.applications;
import java.util.*;
public class ShowConcurrentMutex2 implements Runnable
{
private ArrayList sourceList; // note the type change
private List synchList;
protected static ArrayList upMachineNames() // here too!
{
return new ArrayList
(
Arrays.asList
(
new String[]
{
"Mixer1201",
"ShellAssembler1301",
"StarPress1401",
"UnloadBuffer1501"
}
)
);
}
protected void go()
{
sourceList = upMachineNames();
synchList =
Collections.synchronizedList(sourceList);
List copy;
synchronized (synchList)
{
copy = (List) sourceList.clone();
}
Iterator i = copy.iterator();
int j = 0;
while (i.hasNext())
{
j++;
if (j == 1)
{
new Thread(this).start();
}
System.out.println(i.next());
}
}
Search WWH ::




Custom Search