| Refresh | Home EGTry.com

a simple example to demonstrator the issue of current modification of the iterator of a simple regular list


CopyOnWriteArrayList1Test.java

/*
 * Copyright@ 2011 www.egtry.com
 */

package egtry.thread.collection;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class CopyOnWriteArrayList1Test {

  public static void main(String[] args) {

    List<String> list=new ArrayList<String>();
    for(int i=0; i<5; i++) {
    	list.add("parent "+i);
    }
    Iterator<String> ite=list.iterator();
    String first=ite.next();
    System.out.println("Main "+first);
    Worker worker=new Worker(list);
    worker.start();
    while(ite.hasNext()) {
    	
    	ranSleep(1000);
    
    	System.out.println("Main "+ite.next());
    }

    
  }
  
  public static void ranSleep(int millis) {
	  try {
		  Thread.sleep( (int)(Math.random()*millis));
	  }catch (Exception e) {};
  }
  
  public static class Worker extends Thread {
	  private List<String> list;
	  public Worker(List<String> list) {
		  this.list=list;
	  }
	  
	  @Override
	  public void run() {
		  for(int i=0; i<5; i++) {
			  list.add("child "+i);
			  ranSleep(100);
		  }
		  for(int i=0; i<list.size(); i++) {
			  System.out.println("In Child item="+list.get(i));
		  }
		  
	  }
  }
}



Output

Main parent 0
In Child item=parent 0
In Child item=parent 1
In Child item=parent 2
In Child item=parent 3
In Child item=parent 4
In Child item=child 0
In Child item=child 1
In Child item=child 2
In Child item=child 3
In Child item=child 4