CopyOnWriteArraySet Class in Java

Java Programming Java8Object Oriented Programming

Class declaration

public class CopyOnWriteArraySet<E>
   extends AbstractSet<E>
implements Serializable

CopyOnWriteArraySet class uses CopyOnWriteArrayList internally for all of its operations and thus possesses the basic properties of CopyOnWriteArrayList.

  • CopyOnWriteArraySet is a thread-safe.

  • CopyOnWriteArraySet is to be used in Thread based environment where read operations are very frequent and update operations are rare.

  • Iterator of CopyOnWriteArraySet will never throw ConcurrentModificationException.

  • Any type of modification to CopyOnWriteArraySet will not reflect during iteration since the iterator was created.

  • Set modification methods like remove, set and add are not supported in the iteration. This method will throw UnsupportedOperationException.

CopyOnWriteArraySet Methods

Following is the list of important methods available in the CopyOnWriteArraySet class.

Method & Description
add( )

Adds an object to the collection.

clear( )

Removes all objects from the collection.

contains( )

Returns true if a specified object is an element within the collection.

isEmpty( )

Returns true if the collection has no elements.

iterator( )

Returns an Iterator object for the collection, which may be used to retrieve an object.

remove( )

Removes a specified object from the collection.

size( )

Returns the number of elements in the collection.


Following is an example to explain CopyOnWriteArraySet functionality −

Live Demo

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++) {

      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
      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()) {
      }catch(UnsupportedOperationException e) {
         System.out.println("Method not supported:");
      System.out.println("Size of set: " + set.size());

This will produce the following result −


Initial size of set: 0
Size of set after additions: 5
Contents of set: [34, 22, 10, 60, 30]
Size of set after deletion: 4
Contents of set: [34, 22, 60, 30]
Method not supported:
Size of set: 4
Published on 26-Jul-2018 09:24:08