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.
xxxxxxxxxx
class 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());
}
}