The CopyOnWriteArraySet<E> Class
The CopyOnWriteArraySet class implements the java.util.Set interface (§15.4, p. 804). It does not implement any additional methods. Internally it uses a CopyOnWriteArrayList, and therefore shares the same basic properties with the list, except that, being a set, it does not allow duplicates and its elements have no ordering.
Example 23.21 illustrates the snapshot-style iterator of a CopyOnWriteArrayList. Such a list is created at (1) and populated with three values. A task to traverse the list and print its elements is defined by the Runnable iter at (2). Two threads are created at different times to execute this task at (4) and (6), respectively. The main thread modifies the list by adding a new value and removing a value after the start of the first thread. The output shows that the result from the first thread is not affected by the modifications done by the main thread, as its iterator only traverses those elements that were in the list when the iterator was created. The result from the second thread shows the state of the list when it was created—that is, after the list was modified by the main thread.
Example 23.21 Copy-on-Write Array List
package concurrent;
import java.util.*;
import java.util.concurrent.*;
public class CopyOnWriteArrayListDemo {
public static void main(String[] args) {
List<Integer> cowlist = new CopyOnWriteArrayList<Integer>(); // (1)
cowlist.addAll(Arrays.asList(1, 2, 3));
Runnable iter = () -> { // (2)
String threadName = Thread.currentThread().getName();
for (Integer i : cowlist) {
System.out.println(threadName + “: ” + i);
ConcUtil.snooze(1, TimeUnit.SECONDS);
}
};
// First iterator:
new Thread(iter, “Iterator A”).start(); // (4)
// Snooze, add, and remove in main thread. // (5)
ConcUtil.snooze(1, TimeUnit.SECONDS);
Integer newValue = 4;
cowlist.add(newValue);
System.out.println(“New value added: ” + newValue);
Integer first = cowlist.remove(0);
System.out.println(“Value removed: ” + first);
// Second iterator:
new Thread(iter, “Iterator B”).start(); // (6)
}
}
Probable output from the program:
Iterator A: 1
New value added: 4
Iterator A: 2
Value removed: 1
Iterator B: 2
Iterator A: 3
Iterator B: 3
Iterator B: 4