Java Program to Implement CopyOnWriteArraySet API

This Java program Implements CopyOnWriteArraySet API.A Set which is best suited for 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.It is thread-safe.Mutative operations (add, set, remove, etc.) are expensive since they usually entail copying the entire underlying array.Iterators do not support the mutative remove operation.Traversal via iterators is fast and cannot encounter interference from other threads. Iterators rely on unchanging snapshots of the array at the time the iterators were constructed.

Here is the source code of the Java Program to Implement CopyOnWriteArraySet API.The Java program is successfully compiled and run on a Linux system. The program output is also shown below.

import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
 
public class CopyOnWriteArraySetImpl<E>
{
    private CopyOnWriteArraySet<E> copyOnWriteArraySet;
 
    /** Creates an empty set. **/
    public CopyOnWriteArraySetImpl()
    {
        copyOnWriteArraySet = new CopyOnWriteArraySet<E>();
    }
 
    /**
     * Creates a set containing all of the elements of the specified collection.
    **/
    public CopyOnWriteArraySetImpl(Collection<? extends E> c)
    {
        copyOnWriteArraySet = new CopyOnWriteArraySet<E>(c);
    }
 
    /** adds the specified element if not already present **/
    public boolean add(E eobj)
    {
        return copyOnWriteArraySet.add(eobj);
    }
 
    /** return true if this set contains the specified element **/
    public boolean contains(Object obj)
    {
        return copyOnWriteArraySet.contains(obj);
    }
 
    /** returns true if the set is empty **/
    public boolean isEmpty()
    {
        return copyOnWriteArraySet.isEmpty();
    }
 
    /** returns an iterator over the elements in the set **/
    public Iterator<E> iterator()
    {
        return copyOnWriteArraySet.iterator();
    }
 
    /** removes the specified element from this set if present **/
    public boolean remove(Object obj)
    {
        return copyOnWriteArraySet.remove(obj);
    }
 
    /** returns the number of elements in set **/
    public int size()
    {
        return copyOnWriteArraySet.size();
    }
 
    /** removes all elements from this set **/
    public void clear()
    {
        copyOnWriteArraySet.clear();
    }
 
    /** Returns an array containing all of the elements in this set. **/
    public Object[] toArray()
    {
        return copyOnWriteArraySet.toArray();
    }
 
    /**
     * Adds all of the elements in the specified collection to this set if
     * they're not already present
    **/
    public boolean addAll(Collection<? extends E> c)
    throws UnsupportedOperationException, ClassCastException, NullPointerException, IllegalArgumentException 
    {
        return copyOnWriteArraySet.addAll(c);
    }
 
    /**
     * Retains only the elements in this set that are contained in the specified
     * collection
    **/
    public boolean retainAll(Collection<?> c)
      throws UnsupportedOperationException, ClassCastException, NullPointerException
    {
        return copyOnWriteArraySet.retainAll(c);
    }
 
    /**
     * Removes from this set all of its elements that are contained in the
     * specified collection
    **/
    public boolean removeAll(Collection<?> c)
      throws UnsupportedOperationException, NullPointerException, ClassCastException
    {
        return copyOnWriteArraySet.retainAll(c);
    }
 
    /**
     * Returns an array containing all of the elements in this set; the runtime
     * type of the returned array is that of the specified array
    **/
    public <T> T[] toArray(T[] a) throws ArrayStoreException, NullPointerException
    {
        return copyOnWriteArraySet.toArray(a);
    }
 
    public static void main(String... arg)
    {
        CopyOnWriteArraySetImpl<Integer> copyOnWriteArraySet = new CopyOnWriteArraySetImpl<Integer>();
        if (copyOnWriteArraySet.add(10))
            System.out.println("element 10 added");
        if (copyOnWriteArraySet.add(20))
            System.out.println("element 20 added");
        if (copyOnWriteArraySet.add(30))
            System.out.println("element 30 added");
        System.out.println("the size of copyOnWriteArraySet is " + copyOnWriteArraySet.size());
        if (copyOnWriteArraySet.contains(40))
            System.out.println("copyOnWriteArraySet contains 40");
        else
            System.out.println("copyOnWriteArraySet does not contain 40");
        if (copyOnWriteArraySet.remove(20))
            System.out.println("element 20 removed");
        else
            System.out.println("element 20 not removed");
        System.out.println("the element of copyOnWriteArraySet are");
        Iterator<Integer> iterator = copyOnWriteArraySet.iterator();
        while (iterator.hasNext())
        {
            System.out.print(iterator.next() + "\t");
        }
        System.out.println();
        Set<Integer> removedSet = new HashSet<Integer>();
        removedSet.add(10);
        removedSet.add(20);
        System.out.println("the elements after removing");
        copyOnWriteArraySet.removeAll(removedSet);
        Iterator<Integer> riterator = copyOnWriteArraySet.iterator();
        while (riterator.hasNext()) 
        {
            System.out.print(riterator.next() + "\t");
        }
        System.out.println();
        copyOnWriteArraySet.clear();
        System.out.println("copyOnWriteArraySet cleared");
        if (copyOnWriteArraySet.isEmpty())
            System.out.println("copyOnWriteArraySet is empty");
        else
            System.out.println("copyOnWriteArraySet is not empty");
    }
}
$ javac CopyOnWriteArraySetImpl.java
$ java CopyOnWriteArraySetImpl
element 10 added
element 20 added
element 30 added
the size of copyOnWriteArraySet is 3
copyOnWriteArraySet does not contain 40
element 20 removed
the element of copyOnWriteArraySet are
10	30	
the elements after removing
10	
copyOnWriteArraySet cleared
copyOnWriteArraySet is empty

Related posts:

Java Program to Implement a Binary Search Tree using Linked Lists
Check if a String is a Palindrome in Java
Introduction to Spring Security Expressions
Java Program to Generate All Subsets of a Given Set in the Gray Code Order
Get and Post Lists of Objects with RestTemplate
So sánh ArrayList và LinkedList trong Java
Hướng dẫn Java Design Pattern – Abstract Factory
Java Program to Perform Polygon Containment Test
Spring Security with Maven
Java Program to Perform the Sorting Using Counting Sort
Java Program to Implement Stack using Linked List
Lập trình đa luồng trong Java (Java Multi-threading)
Java Program to Perform Preorder Recursive Traversal of a Given Binary Tree
Introduction to Thread Pools in Java
Java 8 Collectors toMap
Netflix Archaius with Various Database Configurations
Simplify the DAO with Spring and Java Generics
Introduction to Java Serialization
Mệnh đề if-else trong java
Java – InputStream to Reader
Guide to the Java TransferQueue
Java Program to Perform Searching Based on Locality of Reference
Immutable ArrayList in Java
Java Program to Implement Hamiltonian Cycle Algorithm
Java Program to Implement First Fit Decreasing for 1-D Objects and M Bins
Loại bỏ các phần tử trùng trong một ArrayList như thế nào trong Java 8?
Basic Authentication with the RestTemplate
Mockito and JUnit 5 – Using ExtendWith
Java Program to Check Whether an Undirected Graph Contains a Eulerian Cycle
Converting a List to String in Java
Spring Boot - Tracing Micro Service Logs
A Guide to TreeMap in Java