Skip to content
Related Articles

Related Articles

Improve Article

CopyOnWriteArraySet in java

  • Last Updated : 15 Sep, 2020

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. 
 

CopyOnWriteArraySet in java

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

It shares some properties of Set and also has its own properties:

  • The internal implementation of CopyOnWriteArraySet is CopyOnWriteArrayList only.
  • Multiple Threads are able to perform update operation 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 move the control to inbuilt, well tested APIs.

Class Hierarchy:
 

java.lang.Object
   ↳ java.util.AbstractCollection<E>
        ↳ java.util.AbstractSet<E>
             ↳ java.util.concurrent.CopyOnWriteArraySet<E>

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.

Constructors:

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
import java.util.concurrent.*;
import java.util.*;
  
public class ConcurrentDemo extends Thread {
  
    static CopyOnWriteArraySet l = new CopyOnWriteArraySet();
  
    public void run()
    {
        // Child thread trying to add
        // new element in the Set object
        l.add("D");
    }
      
    public static void main(String[] args) 
    {
          // add 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();
        
          // run the child thread
        t.start();
  
        // Wait for the thread to 
        // add the element.
        try {
            Thread.sleep(2000);
        }
        catch (InterruptedException e) {
            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: 
 



[A, B, C, D]
A
B
C
Exception in thread "main" java.lang.UnsupportedOperationException
    at java.util.concurrent.CopyOnWriteArrayList$COWIterator.remove(CopyOnWriteArrayList.java:1176)
    at ConcurrentDemo.main(ConcurrentDemo.java:56)

Iterating over CopyOnWriteArraySet: 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. 

Java




// Java program to illustrate
// Iterating over CopyOnWriteArraySet class
import java.io.*;
import java.util.*;
import java.util.concurrent.*;
  
class IteratingCopyOnWriteArraySet {
    public static void main(String[] args)
    {
          
          // create an instance of
          // CopyOnWriteArraySet
        CopyOnWriteArraySet<String> set
            = new CopyOnWriteArraySet<>();
  
        // Initial Iterator
        Iterator itr = set.iterator();
            
          // add elements using add() method
        set.add("GeeksforGeeks");
            
          // print the contents 
          // of set to the console
        System.out.println("Set contains: ");
        while (itr.hasNext())
            System.out.println(itr.next());
  
        // iterator after adding an element
        itr = set.iterator();
            
          // print the elements to the console
        System.out.println("Set contains:");
        while (itr.hasNext())
            System.out.println(itr.next());
    }
}

 
 

Output:
Set contains: 
Set contains:
GeeksforGeeks

Methods in CopyOnWriteArraySet

  • E – type of elements

METHOD

DESCRIPTION

add(E e)Adds the specified element to this set if it is not already present.
addAll(Collection<? extends E> c)Adds all of the elements in the specified collection to this set if they’re not already present.
clear()Removes all of the elements from this set.
contains(Object o)Returns true if this set contains the specified element.
containsAll(Collection<?> c)Returns true if this set contains all of the elements of the specified collection.
equals(Object o)Compares the specified object with this set for equality.
forEach(Consumer<? super E> action)Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.
isEmpty()Returns true if this set contains no elements.
 iterator()Returns an iterator over the elements contained in this set in the order in which these elements were added.
remove(Object o)Removes the specified element from this set if it is present.
removeAll(Collection<?> c)Removes from this set all of its elements that are contained in the specified collection.
removeIf(Predicate<? super E> filter)Removes all of the elements of this collection that satisfy the given predicate.
retainAll(Collection<?> c)Retains only the elements in this set that are contained in the specified collection.
size()Returns the number of elements in this set.
spliterator()Returns a Spliterator over the elements in this set in the order in which these elements were added.
toArray()Returns an array containing all of the elements in this set.
toArray(T[] a)Returns an array containing all of the elements in this set; the runtime type of the returned array is that of the specified array.

Methods inherited from class java.util.AbstractSet

METHOD

DESCRIPTION

hashCode()Returns the hash code value for this set.

Methods inherited from class java.util.AbstractCollection

METHOD

DESCRIPTION

toString()Returns a string representation of this collection.

Methods inherited from interface java.util.Collection

METHOD

DESCRIPTION

parallelStream()Returns a possibly parallel Stream with this collection as its source.
stream()Returns a sequential Stream with this collection as its source.

HashSet vs CopyOnWriteArraySet

PROPERTY

HashSet

CopyOnWriteArraySet

PackageIt belongs to java.util packageIt belongs to java.util.concurrent package
SynchronizationSynchronization means only one thread can access or modify it. HashSet is not synchronized.It is synchronized.
IteratorsIterators returned my methods iterator() and listiterator() are fail-fast.Iterators returned are fail-safe.
Added In VersionIt was added in JDK 1.2It was added in JDK  1.5
PerformanceIt is fast since it is not synchronized.It is slower compared to HashSet since it is synchronized.
ExceptionIt may throw ConcurrentModificationException since many threads can access it simultaneously. It does not throws ConcurrentModificationException since it is synchronized.

Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/CopyOnWriteArraySet.html




My Personal Notes arrow_drop_up
Recommended Articles
Page :