JavaRush /Java Blog /Random EN /How to use CopyOnWriteArraySet in Java with example (tran...
Lam-lam
Level 30

How to use CopyOnWriteArraySet in Java with example (translation)

Published in the Random EN group
CopyOnWriteArraySetThis is the younger brother of the class CopyOnWriteArrayList. These are 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 package java.util.concurrent. How to use CopyOnWriteArraySet in Java with example (translation) - 1CopyOnWriteArraySetBest suited for read-only collections that are small enough in size to be copied if some modifying operations occur. For example, you could use CopyOnWriteArraySetto store an object when the application starts, and have multiple other threads access that object throughout the application's lifecycle. If a new state or object arrives during this time, it may 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 using CopyOnWriteArrayList. This means it CopyOnWriteArraySetalso shares all the basic properties of CopyOnWriteArrayList. Another important thing to remember is that this collection class's iterators 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 crawling. Traversing this implementation Setusing an iterator is fairly fast and avoids interference from other threads. To operate, iterators rely on a snapshot of the array that was taken when the iterator was created. In short, use CopyOnWriteArraySetif setsmall enough to copy when adding, setting, or deleting objects, and the main purpose is to read sporadically updated data. Also, if you want to remove elements during iteration, do not use this implementation because its iterator does not support remove(), and throws java.lang.UnsupportedOperationException, as shown 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 ready-made Java program showing how to use CopyOnWriteArraySet. In our example, we used the publisher -subscriber pattern to demonstrate its use. Most subscribers are subscribed during the launch of the application 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 a fast bypass, 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 Set, as well as, added in JDK 1.5, along with another custom implementation of Set'a, EnumSet. It is also Setone that uses internal CopyOnWriteArrayListfor all its operations. Thus, it shares the same basic properties of this class. Since it is not SortedSet, the order of elements is not guaranteed during iteration. How to use CopyOnWriteArraySet in Java with example (translation) - 2
  1. CopyOnWriteArraySetBest suited for applications where:

    • The sizes Setof the 's tend to remain small.
    • Operations read-onlyare significantly superior to operations that modify objects.
    • You must prevent interference between threads during traversal Set.
  2. Another advantage CopyOnWriteArraySetis thread safety. This collection supports concurrency.
  3. Mutative operations (adding, modifying, 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 quite fast and during it the interference of other threads is excluded. To operate, iterators rely on a 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, Listthe order of the elements is important and may contain duplicates. While Setunordered, 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, you can use general-purpose implementations. For example, HashSet, LinkedHashSetor synchronized collection classes. Original: How to use CopyOnWriteArraySet in Java with Example
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION