Java CopyOnWriteArraySet Example

Let's discuss example of CopyOnWriteArraySet class from the java.util.concurrent package.
This is a very useful construct in the multi-threaded programs – when we want to iterate over a set in a thread-safe way without an explicit synchronization.

A CopyOnWriteArraySet that uses an internal CopyOnWriteArrayList for all of its operations.

CopyOnWriteArraySet Class Example

This program demonstrates how a CopyOnWriteArraySet works in multi-threading context.

import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * This program demonstrates how a CopyOnWriteArraySet works in multi-threading
 * context.
 *
 * @author www.javaguides.net
 */

public class CopyOnWriteArraySetExample {

    public static void main(final String[] args) {

       final CopyOnWriteArraySet<Integer> set = new CopyOnWriteArraySet<>();

       set.add(1);
       set.add(2);
       set.add(3);
       set.add(4);
       set.add(5);

       final Runnable runnable = () -> {
             set.add(4);
             set.add(5);
       };
  
       final Thread thread = new Thread(runnable);
       thread.start();
  
       final Iterator<Integer> iterator = set.iterator();
       while (iterator.hasNext()) {
             final Integer integer = iterator.next();
             System.out.println(integer);
       }
   }
}
Output:
1
2
3
4
5
Read more examples of CopyOnWriteArraySet class at CopyOnWriteArraySet Class in Java.

Reference

Comments