CopyOnWriteArraySet in Java - GeeksforGeeks

24 Jan, 2022
CopyOnWriteArraySet is a member of the Java Collections Framework. It is a Set that uses an internal CopyOnWriteArrayList for all of its operations. It was introduced in JDK 1.5, we can say that it is a thread-safe version of Set. To use this class, we need to import it from java.util.concurrent package. 
It shares some properties of Set and also has its own properties as listed:
The internal implementation of CopyOnWriteArraySet is CopyOnWriteArrayList only.
Multiple Threads are able to perform update operations simultaneously but for every update operation, a separate cloned copy is created. As for every update a new cloned copy will be created which is costly. Hence if multiple update operations are required then it is not recommended to use CopyOnWriteArraySet.
While one thread iterating the Set, other threads can perform updation, here we won’t get any runtime exception like ConcurrentModificationException.
An Iterator of CopyOnWriteArraySet class can perform only read-only and should not perform the deletion, otherwise, we will get Run-time exception UnsupportedOperationException.
Use CopyOnWriteArraySet in applications in which set sizes generally stay small, read-only operations vastly outnumber mutative operations, and you need to prevent interference among threads during traversal.
CopyOnWriteArraySet helps in minimizing programmer-controlled synchronization steps and moving the control to inbuilt, well-tested APIs.
Class Hierarchy is as follows:
java.lang.Object
   ↳ java.util.AbstractCollection<E>
        ↳ java.util.AbstractSet<E>
             ↳ java.util.concurrent.CopyOnWriteArraySet<E>
Syntax: Declaration
public class CopyOnWriteArraySet<E> extends AbstractSet<E> implements Serializable
Here, E is the type of elements stored in this Collection. It implements Serializable, Iterable<E>, Collection<E>, Set<E> interfaces.
1. CopyOnWriteArraySet(): Creates an empty set.
CopyOnWriteArraySet<E> c = new CopyOnWriteArraySet<E>();
2. CopyOnWriteArraySet(Collection c): Creates a set containing all of the elements of the specified collection.
CopyOnWriteArraySet<E> c = new CopyOnWriteArraySet<E>(Collection c);
Example:
Java
// Java Program to Illustrate CopyOnWriteArraySet Class // Importing required classesimport java.util.*;import java.util.concurrent.*; // Main classclass ConcurrentDemo extends Thread {     static CopyOnWriteArraySet l        = new CopyOnWriteArraySet();     // Method    public void run()    {        // Child thread trying to add        // new element in the Set object        l.add("D");    }     // Method 2    // Main driver method    public static void main(String[] args)    {         // Adding elements        // using add() method        l.add("A");        l.add("B");        l.add("C");         // We create a child thread        // that is going to modify        // CopyOnWriteArraySet l.        ConcurrentDemo t = new ConcurrentDemo();         // Running the child thread        // using start() method        t.start();         // Waiting for the thread to        // add the element         // Try block to check for exceptions        try {             Thread.sleep(2000);        }         // Catch block to handle exceptions        catch (InterruptedException e) {             // Print statement            System.out.println(                "child going to add element");        }         System.out.println(l);         // Now we iterate through the        // CopyOnWriteArraySet and we        // wont get exception.        Iterator itr = l.iterator();         while (itr.hasNext()) {             String s = (String)itr.next();            System.out.println(s);             if (s.equals("C")) {                 // Here we will get                // RuntimeException                itr.remove();            }        }    }}
 Output: 
We can iterate over the elements contained in this set in the order in which these elements were added using the iterator() method. The returned iterator provides an immutable snapshot of the state of the set when the iterator was constructed. Because of this property, GeeksforGeeks is not printed at the first iteration. Synchronization is not required while iterating. The iterator does not support the remove method. 
Example:
Java
// Java program to Illustrate Iterating Over// CopyOnWriteArraySet class // Importing required classesimport java.io.*;import java.util.*;import java.util.concurrent.*; // Main class// IteratingCopyOnWriteArraySetclass GFG {     // Main class    public static void main(String[] args)    {         // Creating an instance of CopyOnWriteArraySet        CopyOnWriteArraySet<String> set            = new CopyOnWriteArraySet<>();         // Initial an iterator        Iterator itr = set.iterator();         // Adding elements        // using add() method        set.add("GeeksforGeeks");         // Display message only        System.out.println("Set contains: ");         // Printing the contents        // of set to the console        while (itr.hasNext())            System.out.println(itr.next());         // Iterator after adding an element        itr = set.iterator();         // Display message only        System.out.println("Set contains:");         // Printing the elements to the console        while (itr.hasNext())            System.out.println(itr.next());    }}
Set contains: 
Set contains:
GeeksforGeeks
Method
Action Performed
METHOD
DESCRIPTION
METHOD
DESCRIPTION
METHOD
DESCRIPTION
PROPERTY
HashSet
CopyOnWriteArraySet
surendapandey3788
Ganeshchowdharysadanala
solankimayank
Java - util package
Java-Collections
Java-CopyOnWriteArraySet
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java
HashMap in Java with Examples
Object Oriented Programming (OOPs) Concept in Java
Interfaces in Java
Initialize an ArrayList in Java
ArrayList in Java