Sunday, August 26, 2012

CopyOnWriteArrayList difference with normal ArrayList

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.

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");
}
}
}

Related Posts:

  • Command execution by Java Processorsample code to execute any command on operating system by using java processor. for example : To find jdk installed in system, We can run the command "where javac" for window and "where is javac" for linux the above command… Read More
  • Java get system environment variable detailsGet System environment variable details. import java.util.Map; /** * * @author Uttesh Kumar T.H. */ public class FindJdk { public static void main(String[] args) { Map<String, String> env = System.gete… Read More
  • Spring + JPA + Hibernate Sample IntroductionStand-alone Spring application sample, Spring framework supports the persistence layer to be fully implemented through JPA. Simple example of configure the Spring needed components to perform persistence over sta… Read More
  • Generate PDF page as imageWe can generate the image of pdf page by using the Pdf-renderer Simple class which generate the images file of given pdf file. /* * To change this license header, choose License Headers in Project Properties. * To change … Read More
  • 6 Steps for contribute your jar/project to open source maven repository Prerequisites: 1. Sign Up at Sonatype. 2. Create your project in JIRA. 3. Create a Key Pair. 4. Create and Sign your Artifacts. 5. Deploy your Artifacts to your Staging Repository. 6. Promote your Repository Step #1: Sign Up… Read More

0 comments:

Post a Comment