Thread-Safe Iterators

When it returns the next value in a collection to a client, an iterator also returns control of the program. This opens the possibility that a client will take an action that will change the collection over which you are iterating. Consider a program that can update a list in one thread while another thread is iterating over the list:

package com.oozinoz.applications;
import java.util.*;
public class ShowConcurrentFor implements Runnable { private List list; protected static List upMachineNames() { return new ArrayList ( Arrays.asList ( new String[] { "Mixer1201", "ShellAssembler1301", "StarPress1401", "UnloadBuffer1501" } ) ); } protected void go() { list = Collections.synchronizedList( upMachineNames()); for (int i = ...

Get Design Patterns Java™ Workbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.