ArrayList - synchronizing using Collections.synchronizedList








ArrayList - synchronizing using Collections.synchronizedList in java.


Iterator on synchronizedList won't be synchronized, so will have to synchronize list using synchronization block during iteration in java.



import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/**
* Copyright (c), AnkitMittal JavaMadeSoEasy.com
*/
public class ArrayListTest {
   public static void main(String args[]) {
          // creates array with initial capacity of 10.
          List<String> arrayList = new ArrayList<String>();
          arrayList.add("ankit");
          arrayList.add("javaMadeSoEasy");
          // getting synchronized ArrayList
          List<String> synchronizedList = Collections.synchronizedList(arrayList);
         
         
          //Iterator on synchronizedList won't be synchronized, so will have to
          //synchronize list using synchronization block during iteration
            System.out.println("------- iterating on synchronized list -------");
            synchronized(synchronizedList){
          Iterator<String> iterator = synchronizedList.iterator();
          while (iterator.hasNext()) {
                 System.out.println(iterator.next());
          }            
     }
   }
}
/*OUTPUT
------- iterating on synchronized list -------
ankit
javaMadeSoEasy
*/



RELATED LINKS>

ArrayList - add, add element at specific index methods program


ArrayList - remove, get, contains and set methods program


ArrayList - iterate using iterator, listIterator, Enumeration and enhanced for loop


ArrayList - making list unmodifiable using Collections.unmodifiableList


Vector - add, add element at specific index methods program


eEdit
Must read for you :