CopyOnWriteArraySet in Java

CopyOnWriteArraySet in Java | It is the part of java.util.concurrent package and works as a synchronized version of the Set. Also see:- CopyOnWriteArrayList In Java, ConcurrentMap Interface in Java

  • Collection(I)
    • Set(I)
      • CopyOnWriteArraySet
  1. It is the thread-safe version of Set.
  2. Insertion order is preserved.
  3. Duplicate objects are not allowed.
  4. Multiple threads can perform read operation simultaneously but for every update operation a separate cloned copy will be created.
  5. As for every update operation a separate cloned copy will be created which is costly hence if multiple update operations are required then it is not recommended to use CopyOnWriteArraySet.
  6. While one thread iterates Set the other threads are allowed to modify Set and won’t get ConcurrentModificationException.
  7. The iterator of CopyOnWriteArraySet can perform only the read operation and won’t perform any remove operation otherwise we will give UnSupportedOperationException.

Constructors of CopyOnWriteArraySet

  • CopyOnWriteArraySet();
  • CopyOnWriteArraySet(Collection c);

It doesn’t contain any specific methods.

Example Program

import java.util.concurrent.CopyOnWriteArraySet;
public class Test {
   public static void main(String[] args) {
      CopyOnWriteArraySet<String> cas = 
           new CopyOnWriteArraySet<String>();
      cas.add("D");
      cas.add("B");
      cas.add("C");
      cas.add("A");
      cas.add(null);
      cas.add("D");
      System.out.println(cas); // [D, B, C, A, null]
   }
}

Difference between CopyOnWriteArraySet and synchronizedSet()

CopyOnWriteArraySetSynchronizedSet()
It is thread-safe because every update operation will be performed on a separate cloned copy.It is thread-safe because at a time only one thread can perform operation.
While one thread iterating Set, the other threads are allowed to modify and we won’t get ConcurrentModificationException.While one thread iterating, the other threads are not allowed to modify Set otherwise we will get CurrentModificationException.
Iterator is fail-safe.Iterator is fail fast.
Iterator can perform only read operation and can’t perform remove operation otherwise we will get RuntimeException saying UnsupportedOperationException.Iterator can perform both read and remove operations.
It was introduced in the 1.5 version.It was introduced in the 1.2 version.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *