CopyOnWriteArraySetis the younger brother of the class CopyOnWriteArrayList. This is a specialized set of classes added in JDK 1.5 along with their more popular cousin ConcurrentHashMap. They are part of concurrent collection frameworkand located in the java.util.concurrent. How to use CopyOnWriteArraySet in Java with an example (translation) - 1CopyOnWriteArraySetbest suited for read-only collections that are small enough to be copied if some mutating operation occurs. For example, you can use it CopyOnWriteArraySetto store an object at application startup, and give multiple other threads access to that object throughout the life of the application. If a new state or object arrives within this time, it can also be added to this one Set, at the cost of creating a new array. One of the most important things to know about CopyOnWriteArraySetis that it is implemented usingCopyOnWriteArrayList. This means that it CopyOnWriteArraySetalso shares all the basic properties of CopyOnWriteArrayList. Another important thing to remember is that the iterators of this collection class do not support the remove(). Attempting to remove an element during integration will result in an outlier UnsupportedOperationException. This is done to ensure speed during the traversal. Traversing this implementation Setusing an iterator is fast enough to avoid interference from other threads. Iterators rely on the snapshot of the array that was taken when the iterator was created. In short, use CopyOnWriteArraySetifsetsmall enough to be copied when objects are added, set, or removed, and the main purpose is to read data that is updated on an occasional basis. Also, if you want to remove elements while iterating, don't use this implementation because its iterator doesn't support remove(), and throws java.lang.UnsupportedOperationException, like below:
[RAJ] Event received : FOUR
Exception in thread "main" java.lang.UnsupportedOperationException
    at java.util.concurrent.CopyOnWriteArrayList$COWIterator.remove(Unknown Source)
    at Publisher.notifySubs(HelloHP.java:43)
    at HelloHP.main(HelloHP.java:23)

CopyOnWriteArraySet example in Java

Here is a finished Java program showing how to use CopyOnWriteArraySet. In our example, we used the publisher -subscriber pattern to demonstrate its use. Most of the subscribers are subscribed at application launch and the main task of the publisher is to enumerate them and notify them of any updates. Subscriber additions and deletions may occur from time to time. Since we need fast traversal, CopyOnWriteArraySetthis is a good choice, especially in a multi-threaded environment where one thread can add a subscriber while another thread handles updates.
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * Java program to demonstrate how to use CopyOnWriteArraySet in Java. Remember,
 * CopyOnWriteArraySet doesn't support remove() operation.
 *
 * @author Javin Paul
 */
public class CopyOnWriteArraySetDemo{

    public static void main(String args[]) {
        Publisher cricNext = new Publisher();

        SubScriber raj = new SubScriber("RAJ");
        SubScriber adom = new SubScriber("ADOM");

        cricNext.addSubscriber(raj);
        cricNext.addSubscriber(adom);

        cricNext.notifySubs("FOUR");
        cricNext.notifySubs("SIX");

    }

}

class Publisher {

    private CopyOnWriteArraySet setOfSubs = new CopyOnWriteArraySet();

    public void addSubscriber(SubScriber sub) {
        setOfSubs.add(sub);
    }

    public void notifySubs(String score) {
        Iterator itr = setOfSubs.iterator();
        while (itr.hasNext()) {
            SubScriber sub = itr.next();
            sub.receive(score);

            //itr.remove(); // not allowed, throws UnsupportedOperationException
        }
    }
}

class SubScriber {

    private String _name;

    public SubScriber(String name) {
        this._name = name;
    }

    public void receive(String score) {
        System.out.printf("[%s] Event received : %s %n", _name, score);
    }
}
output:
[RAJ] Event received : FOUR
[ADOM] Event received : FOUR
[RAJ] Event received : SIX
[ADOM]Event received : SIX

What to remember

CopyOnWriteArraySetimplements the Collectionand interfaces Setas well, added in JDK 1.5, along with another special implementation of Set'a, EnumSet. It's also Setthe one that uses the internal CopyOnWriteArrayListfor all of its operations. So it shares the same basic properties of that class. Since it is not SortedSet, the order of the elements is not guaranteed during the iteration. How to use CopyOnWriteArraySet in Java with an example (translation) - 2
  1. CopyOnWriteArraySetbest suited for applications where:

    • The sizes Setof 's tend to remain small.
    • Operations read-onlyare far superior to operations that modify objects.
    • You must prevent interference between threads during the traversal Set.
  2. Another benefit CopyOnWriteArraySetis thread safety. This collection supports concurrency.
  3. Mutative operations (adding, changing, deleting, etc.) are expensive because they typically require copying the entire underlying array.
  4. Iterators do not support the mutative delete operation.
  5. Traversal using an iterator is fast enough and interference from other threads is excluded during it. Iterators rely on the snapshot of the array that was taken when the iterator was created.
That's all about usage CopyOnWriteArraySetin Java. As I said, he is the younger brother CopyOnWriteArrayList. So if you understand at least one of them, you can use the other. The only difference is that one is List' and the other Setis ', so this entails inheriting all the differences between these data structures in Java. For example, in Listthe order of the elements is important, and it may contain duplicates. While Setis unordered, it does not allow duplication of objects. Always remember that CopyOnWriteArraySetthis is a specialized Collectionclass. It should only be used when conditions are favorable. In any other case, general-purpose implementations can be used. For example HashSet,LinkedHashSetor synchronized collection classes. Original: How to use CopyOnWriteArraySet in Java with Example