Walking on water and developing software from a specification are easy if both are frozen.Edward V Berard Edward V Berard
A Set that uses an internal CopyOnWriteArrayList for all of its operations. It is useful when the list shares the data structure among several threads and have few writes and many reads.
![]() |
CopyOnWriteArraySet uses CopyOnWriteArrayList for all of its operations. |
![]() |
It is Thread safe. |
![]() |
The iteration does not support remove operations. |
![]() |
Support putidAbsent atomic operation, checks whether an equal element is already in the list and adds it only if it is not. |
package com.careerdrill.collections.set; import java.util.Iterator; import java.util.concurrent.CopyOnWriteArraySet; public class CopyOnWriteArraySetUse { private final CopyOnWriteArraySet< String > cwas = new CopyOnWriteArraySet< String >(); public static void main(String... args){ CopyOnWriteArraySetUse ob= new CopyOnWriteArraySetUse(); System.out.println("Add 1 to the CopyOnWriteArraySet and pass to Thread"); ob.cwas.add("1"); new Thread(ob.new modifyThread(),"Thread1").start(); new Thread(ob.new modifyThread(), "Thread2").start(); } class modifyThread implements Runnable { @Override public void run() { Iterator< String > itr= cwas.iterator(); String s=itr.next(); cwas.removeAll(cwas); cwas.add(s+"2"); itr= cwas.iterator(); System.out.println("Update the value on CopyOnWriteArraySet "+ itr.next() +" from thread "+Thread.currentThread().getName()); } } }
Add 1 to the CopyOnWriteArraySet and pass to Thread Update the value on CopyOnWriteArraySet 12 from thread Thread1 Update the value on CopyOnWriteArraySet 122 from thread Thread2
CopyOnWriteArraySet | ConcurrentSkipListSet |
---|---|
Uses CopyOnWriteArrayList for all of its operations. | Implementation based on a ConcurrentSkipListMap. |
Thread-safe. | Execute concurrently by multiple threads. |
Do not throw ConcurrentModificationException. | Do not throw ConcurrentModificationException. |
Traversal via iterators is fast and cannot encounter interference from other threads. | Returns an iterator over the elements in this set in ascending order. |
When set sizes generally stay small, read-only operations vastly outnumber mutative operations, you can choose CopyOnWriteArraySet. When you want to share the data structure among several threads and have few writes and many reads.
0 Comments