CopyOnWriteArraySet
This 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 framework
and located in the package
java.util.concurrent
.
CopyOnWriteArraySet
Best suited for read-only collections that are small enough in size to be copied if some modifying operations occur. For example, you could use
CopyOnWriteArraySet
to 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
CopyOnWriteArraySet
is that it is implemented using
CopyOnWriteArrayList
. This means it
CopyOnWriteArraySet
also 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
Set
using 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
CopyOnWriteArraySet
if
set
small 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,
CopyOnWriteArraySet
this 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;
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);
}
}
}
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
CopyOnWriteArraySet
implements the
Collection
and interfaces
Set
, as well as, added in JDK 1.5, along with another custom implementation of
Set
'a,
EnumSet
. It is also
Set
one that uses internal
CopyOnWriteArrayList
for 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.
-
CopyOnWriteArraySet
Best suited for applications where:
- The sizes
Set
of the 's tend to remain small.
- Operations
read-only
are significantly superior to operations that modify objects.
- You must prevent interference between threads during traversal
Set
.
- Another advantage
CopyOnWriteArraySet
is thread safety. This collection supports concurrency.
- Mutative operations (adding, modifying, deleting, etc.) are expensive because they typically require copying the entire underlying array.
- Iterators do not support the mutative delete operation.
- 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
CopyOnWriteArraySet
in 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
Set
is '', so this entails inheriting all the differences between these data structures in Java. For example,
List
the order of the elements is important and may contain duplicates. While
Set
unordered, it does not allow duplication of objects. Always remember that
CopyOnWriteArraySet
this is a specialized
Collection
class. It should only be used when conditions are favorable. In any other case, you can use general-purpose implementations. For example,
HashSet
,
LinkedHashSet
or synchronized collection classes. Original:
How to use CopyOnWriteArraySet in Java with Example
GO TO FULL VERSION