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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.