Java Concurrent Collection - CopyOnWriteArraySet Example
- Details
- Written by Nam Ha Minh
- Last Updated on 13 August 2019   |   Print Email
- It’s a thread-safe, and can be used as a thread-safe alternative to HashSet.
- It allows sequential write and concurrent reads by multiple threads. Only one thread can execute write operations (add and remove), and multiple threads can execute read operations (iterator) at a time.
- Its iterator doesn’t throw ConcurrentModificationException and doesn’t support remove method.
- Thread Writer adds a number to CopyOnWriteArraySet for every 5 seconds.
- Thread Reader iterates the list repeatedly with a small delay (10 milliseconds) for every iteration.
Here’s the full source code of the program:import java.util.*; import java.util.concurrent.*; /** * This program demonstrates how a CopyOnWriteArraySet works * in multi-threading context. * * @author www.codejava.net */ public class CopyOnWriteArraySetTest { public static void main(String[] args) { Set<Integer> set = new CopyOnWriteArraySet<>(); set.add(1); set.add(2); set.add(3); set.add(4); set.add(5); new WriteThread("Writer", set).start(); new ReadThread("Reader", set).start(); } } class WriteThread extends Thread { private Set<Integer> set; public WriteThread(String name, Set<Integer> set) { this.set = set; super.setName(name); } public void run() { int count = 6; while (true) { try { Thread.sleep(5000); } catch (InterruptedException ex) { ex.printStackTrace(); } set.add(count++); System.out.println(super.getName() + " done"); } } } class ReadThread extends Thread { private Set<Integer> set; public ReadThread(String name, Set<Integer> set) { this.set = set; super.setName(name); } public void run() { while (true) { String output = "\n" + super.getName() + ":"; Iterator<Integer> iterator = set.iterator(); while (iterator.hasNext()) { Integer next = iterator.next(); output += " " + next; // fake processing time try { Thread.sleep(10); } catch (InterruptedException ex) { ex.printStackTrace(); } } System.out.println(output); } } }You can see that the read operations outnumber the write ones.
Set<Integer> set = new HashSet<>();Recompile and run the program again, you will see that the reader thread throws ConcurrentModificationException as soon as the writer thread adds a new element to the list. The reader thread die and only the writer thread alive.
Other Java Concurrent Collections:
Other Java Concurrency Tutorials:
- How to use Threads in Java (create, start, pause, interrupt and join)
- Java Synchronization Tutorial
- Understanding Deadlock, Livelock and Starvation with Code Examples in Java
- Understanding Java Fork-Join Framework with Examples
- Understanding Atomic Variables in Java
Comments