CopyOnWriteArraySet is a Set that uses an internal CopyOnWriteArrayList for all of its operations. It is introduced in JDK 1.5, we can say that it is thread-safe version of Set.
It share some properties of Set and also has its own properties:
- The internal implementation of CopyOnWriteArraySet is CopyOnWriteArrayList only.
- Insertion order is preserved and duplicates are allowed.
- Multiple Threads are able to perform update operation simultaneously but for every update operation a separate cloned copy is created. As for every update a new cloned copy will be created which is costly. Hence if multiple update operation are required then it is not recommended to use CopyOnWriteArraySet.
- While one thread iterating the Set, other threads can perform updation, here we wont get any runtime exception like ConcurrentModificationException.
- Iterator of CopyOnWriteArraySet class can perform only read only and wont perform deletion, otherwise we will get Run-time exception UnsupportedOperationException.
Constructors of CopyOnWriteArraySet:
- CopyOnWriteArraySet c = new CopyOnWriteArraySet(): Creates an empty set.
- CopyOnWriteArraySet c = new CopyOnWriteArraySet(Collection c): Creates a set containing all of the elements of the specified collection.
NOTE: All methods of CopyOnWriteArraySet is extended from the Collections only because Set interface does not contain any specific methods. CopyOnWriteArraySet does not contain any new methods.
[A, B, C, D] A B C Exception in thread "main" java.lang.UnsupportedOperationException
- Difference between HashMap and ConcurrentHashMap
- Difference between ArrayList and CopyOnWriteArrayList
- CopyOnWriteArrayList in java
- Producer-Consumer solution using Semaphores in Java | Set 2
- Hashtable in Java
- Lifecycle and States of a Thread in Java
- Decision Making in Java (if, if-else, switch, break, continue, jump)
- Anonymous Inner Class in Java
- Java.io.File Class in Java
- Synchronization of ArrayList in Java
- Comparable vs Comparator in Java
- String class in Java | Set 1
- Generics in Java
- Overriding toString() in Java
- final variables in Java
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.