Table of contents
1.
Introduction
2.
Properties
3.
Class Hierarchy
3.1.
Syntax
4.
Constructors of CopyOnWriteArraySet
4.1.
Program
4.2.
Output
5.
Iterating over CopyOnWriteArraySet
5.1.
Program
5.2.
Output
6.
Methods in CopyOnWriteArraySet
7.
FAQs
8.
Conclusion
Last Updated: Mar 27, 2024

CopyOnWriteArraySet

Author Anjali
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In this article, we will be discussing a crucial concept related to CopyOnWriteArraySet and its methods. This is a member of the Java Collections Framework. The CopyOnWriteArraySet class uses CopyOnWriteArrayList internally for all its operations, thus it possesses the basic properties of CopyOnWriteArrayList. It was introduced in JDK 1.5, and it is a thread-safe version of set. To use this class, import it from java.util.concurrent package. 

You can also read about the Multiple Inheritance in Java.

Properties

  1. The internal implementation of CopyOnWriteArraySet is CopyOnWriteArrayList.
  2. 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.
  3. While one thread iterating the Set, other threads can perform update, and here we won’t get any runtime exception like ConcurrentModificationException.
  4. An Iterator of CopyOnWriteArraySet class can perform only read-only and should not perform the deletion. Otherwise, we will get Run-time exception UnsupportedOperationException.
  5. CopyOnWriteArraySet should be used in Thread based environment where read operations are very frequent, and update operations are rare.
  6. CopyOnWriteArraySet is best suited for the 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.
  7. CopyOnWriteArraySet helps in minimizing programmer-controlled synchronization steps and moving the control to inbuilt, well-tested APIs.
    Also Read About, Multithreading in java

Class Hierarchy

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

Syntax

public class CopyOnWriteArraySet<E>
   extends AbstractSet<E>
implements Serializable
You can also try this code with Online Java Compiler
Run Code

Here, E is the type of elements stored in the Collection. It implements Serializable, Iterable<E>, Collection<E>, Set<E> interfaces.

Constructors of CopyOnWriteArraySet

1. CopyOnWriteArraySet(): This creates an empty set.

CopyOnWriteArraySet<E> c = new CopyOnWriteArraySet<E>();

2. CopyOnWriteArraySet(Collection c): This creates a set containing all of the elements of the specified collection.

CopyOnWriteArraySet<E> c = new CopyOnWriteArraySet<E>(Collection c);

Program

// Java Program to Illustrate CopyOnWriteArraySet Class
 
// Importing required classes
import java.util.*;
import java.util.concurrent.*;
 
// Main class
class ConcurrentDemo extends Thread {
 
    static CopyOnWriteArraySet  s = new CopyOnWriteArraySet();
 
    // Method
    public void run()
    {
        // Child thread trying to add a new element in the Set object
        s.add("Element4");
    }
 
    //Main driver method
    public static void main(String[] args)
    {
 
        // Adding elements using add() method
        s.add("Element1");
        s.add("Element2");
        s.add("Element3");
 
        // Creating a child thread that is going to modify CopyOnWriteArraySet s.
        ConcurrentDemo t = new ConcurrentDemo();
 
        // Running child thread using start() method
        t.start();
 
        // Waiting for thread to add the element
 
        // Try block to check the exceptions
        try {
            Thread.sleep(2000);
        }
 
        // Catch block to handle the exceptions
        catch (InterruptedException e) {
 
            // Print statement
            System.out.println("Child is going to add the element");
        }
 
        System.out.println(s);
 
        // Now we iterate through the CopyOnWriteArraySet without getting exception.
        Iterator itr = s.iterator();
 
        while (itr.hasNext()) {
 
            String s = (String)itr.next();
            System.out.println(s);
 
            if (s.equals("Element3")) {
 
                // Here we will get RuntimeException
                itr.remove();
            }
        }
    }
}
You can also try this code with Online Java Compiler
Run Code

Output

Try it by yourself on java online compiler.

Iterating over CopyOnWriteArraySet

Iteration over the elements contained in this set in the order in which these elements were added can be done using the iterator() method. The iterator returned provides an immutable snapshot of the state of set when iterator was constructed. Synchronization is not required while iterating. The iterator does not supports remove method.

Program

// Java program to Illustrate Iterating Over CopyOnWriteArraySet class

// Importing required classes
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArraySet;

public class Tester {

   public static void main(String args[]) {
      // create an array list
      CopyOnWriteArraySet<Integer> set = new CopyOnWriteArraySet();
      System.out.println("Initial size of set: " + set.size());
      int count[] = {34, 22,10,60,30,22};
      // add elements to the array list
      for(int i = 0; i < 5; i++) {
         set.add(count[i]);
      }

      System.out.println("Size of set after additions: " + set.size());

      // display the set
      System.out.println("Contents of set: " + set);

      // Remove elements from the array list
      set.remove(10);
      System.out.println("Size of set after deletion: " + set.size());
      System.out.println("Contents of set: " + set);

      try {
         Iterator<Integer> iterator = set.iterator();
         while(iterator.hasNext()) {
            iterator.remove();
         }
      }
      catch(UnsupportedOperationException e) {
         System.out.println("Method not supported:");
      }
      System.out.println("Size of set: " + set.size());
   }
}
You can also try this code with Online Java Compiler
Run Code

Output

Methods in CopyOnWriteArraySet

FAQs

  1. When is CopyOnWriteArraySet useful to achieve thread-safe HashSet?
    It is useful when you have a small set of elements for a thread-safe collection.
     
  2. What is the hashCode() method?
    It is a method inherited from class java.util.AbstractSet, which returns the hash code value for the set.
     
  3. Which is fast among HashSet and CopyOnWriteArraySet?
    HashSet is fast as it is not synchronised while in comparison, CopyOnWriteArraySet is slow as it is synchronised.
     
  4. Which methods are inherited from interface java.util.Collection?
    parallelStream() and stream() methods are inherited from interface java.util.Collection.

Conclusion

In this blog, we have discussed CopyOnWriteArraySet. We discussed the syntax, constructors of the CopyOnWriteArraySet. Then we discussed the way of iteration over CopyOnWriteArraySet and various other methods of the class CopyOnWriteArraySet.

Recommended problems -



We hope that this blog helped you enhance your knowledge regarding CopyOnWriteArraySet. Learning never stops, and to learn more and become more skilled, head over to our practice platform Coding Ninjas Studio, to practice top problems, attempt Mock Tests, read informative blogs and interview experiences. Do upvote our blog to help other ninjas grow. 

Happy Learning!

Live masterclass