Fundamentals of CopyOnWriteArrayList and CopyOnWriteArraySet
[1.] The basic thing behind the CopyOnWriteArrayList and CopyOnWriteArraySet is all mutable operations make a copy of the backing array first, make the change to the copy, and then replace the copy.
[2]. If we want to share the data structure among several threads where we have few writes and many reads then we can use CopyOnWriteArrayList and CopyOnWriteArraySet.
[3]. The CopyOnWrite... collections avoid ConcurrentModificationException issues during traversal by traversing through the original collection and the modifications happening in a copy of the original store.
[4]. CopyOnWriteArrayList is a thread-safe version of ArrayList without the syncrhonized access limitations. Both are available in java.util.concurrent package.
//Sample example of CopyOnWriteArrayList which is used to avoid ConcurrentModificationException and UnsupportedOperationException
package com.corejava.gaurav.examples;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.concurrent.CopyOnWriteArrayList;
public class CopyOnWriteArrayListTestExample {
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String args[]){
CopyOnWriteArrayList clst = new CopyOnWriteArrayList();
clst.add("Shivam");
clst.add("Priyanka");
ListIterator itr = clst.listIterator();
while(itr.hasNext()){
System.out.println("Elements are->"+itr.next());
clst.add("Dhanush");
}
Iterator itr1 = clst.iterator();
while(itr1.hasNext()){
System.out.println("after Modification Elements are->"+itr1.next());
}
}
}
//Sample example of CopyOnWriteArraySet which is used to avoid ConcurrentModificationException and UnsupportedOperationException
package com.corejava.gaurav.examples;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArraySet;
public class CopyOnWriteArraySetTestExample {
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String args[]){
CopyOnWriteArraySet cset = new CopyOnWriteArraySet();
cset.add("Mitali");
cset.add("Nikhil");
Iterator itr = cset.iterator();
while(itr.hasNext()){
System.out.println("Set Elements are-"+itr.next());
cset.add("Vishal");
}
Iterator itr1 = cset.iterator();
while(itr1.hasNext()){
System.out.println("After Modification Set Elements are-"+itr1.next());
}
}
}
No comments:
Post a Comment