CopyOnWriteArraySet
is 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 framework
and located in the
java.util.concurrent
.
CopyOnWriteArraySet
best suited for read-only collections that are small enough to be copied if some mutating operation occurs. For example, you can use it
CopyOnWriteArraySet
to 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
CopyOnWriteArraySet
is that it is implemented using
CopyOnWriteArrayList
. This means that it
CopyOnWriteArraySet
also 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
Set
using 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
CopyOnWriteArraySet
if
set
small 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,
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, added in JDK 1.5, along with another special implementation of
Set
'a,
EnumSet
. It's also
Set
the one that uses the internal
CopyOnWriteArrayList
for 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.
-
CopyOnWriteArraySet
best suited for applications where:
- The sizes
Set
of 's tend to remain small.
- Operations
read-only
are far superior to operations that modify objects.
- You must prevent interference between threads during the traversal
Set
.
- Another benefit
CopyOnWriteArraySet
is thread safety. This collection supports concurrency.
- Mutative operations (adding, changing, 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 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
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, in
List
the order of the elements is important, and it may contain duplicates. While
Set
is 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, general-purpose implementations can be used. For example
HashSet
,
LinkedHashSet
or synchronized collection classes. Original:
How to use CopyOnWriteArraySet in Java with Example
GO TO FULL VERSION