CopyOnWriteArraySet (Thread safe HashSet) Example

CopyOnWriteArraySet is a thread safe Set implementation and it is suitable for applications in which set sizes generally stay small read only operations and needs to prevent interference among threads during traversal.

Example

package com.vinod.concurrency;
import java.util.HashSet;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArraySet;
public class CopyOnArraySetExample {
	// ThreadSafe Set implemenation as part of java concurrency api
	public static void main(String[] args) {
		HashSet<String> al = new HashSet<String>();
		al.add("sunday");
		al.add("monday");
		al.add("tuesday");
		Iterator<String> alIterator = al.iterator();
		while (alIterator.hasNext()) {
			String value = alIterator.next();
			al.add("wednesday");
		}
		System.out.println(al);
		CopyOnWriteArraySet<String> coal = new CopyOnWriteArraySet<String>();
		coal.add("sunday");
		coal.add("monday");
		coal.add("tuesday");
		Iterator<String> coalIterator = coal.iterator();
		while (coalIterator.hasNext()) {
			String value = coalIterator.next();
			coal.add("wednesday");
		}
		System.out.println(coal);
	}
}

Output


Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.HashMap$HashIterator.nextEntry(HashMap.java:806)
    at java.util.HashMap$KeyIterator.next(HashMap.java:841)
    at com.vinod.concurrency.CopyOnArraySetExample.main(CopyOnArraySetExample.java:17)


This exception is from HashSet iteration, during iteration we are trying to add values and it is throwing ConcurrentModificationException.
Comment below line and run it again.


//al.add("wednesday");


Output


[monday, sunday, tuesday]
[sunday, monday, tuesday, wednesday]

No comments:

Post a Comment

Confusion Matrix + Precision/Recall (Super Simple, With Examples)

  Confusion Matrix + Precision/Recall (Super Simple, With Examples) 1) Binary Classification Setup Binary classification means the model p...

Featured Posts