CopyOnWriteArrayList was introduced in JDK5, Which will be used to avoid the java.util.ConcurrentModificationException while modifying List by multiple threads or inside loop.
below sample will show the difference.
below sample will show the difference.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.Iterator; | |
import java.util.List; | |
import java.util.concurrent.CopyOnWriteArrayList; | |
/* | |
* Difference between ArrayList and CopyOnWriteArrayList | |
*/ | |
public class CopyOnWriteArrayListTest { | |
public static void main(String[] args) { | |
CopyOnWriteArrayList copyOnWriteArrayList = new CopyOnWriteArrayList(); | |
copyOnWriteArrayList.add("copyOnWriteArrayList_item"); | |
copyOnWriteArrayList.add("copyOnWriteArrayList_item1"); | |
Iterator iCopyIterator = copyOnWriteArrayList.iterator(); | |
while (iCopyIterator.hasNext()) { | |
//System.out.println(iCopyIterator.next()); | |
iCopyIterator.next(); | |
copyOnWriteArrayList.add("copyOnWriteArrayList_item2"); | |
} | |
System.out.println("|---- After modification of copyOnWriteArrayList ----| "); | |
Iterator i2 = copyOnWriteArrayList.iterator(); | |
while (i2.hasNext()) { | |
System.out.println(i2.next()); | |
} | |
/* | |
* If List modified in the loop iteration it will throw | |
* ConcurrentModificationException or if multiple threads try to modify | |
* the List in loop iteration will throw the exception for normal arrayList | |
*/ | |
List list = new ArrayList(); | |
list.add("test"); | |
list.add("test1"); | |
Iterator listIterator = list.iterator(); | |
while (listIterator.hasNext()) { | |
System.out.println(listIterator.next()); | |
list.add("test2"); | |
} | |
} | |
} |
0 comments:
Post a Comment