LinkedList - synchronizing using Collections.synchronizedList in java




LinkedList - synchronizing using Collections.synchronizedList.


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

import java.util.Iterator;
import java.util.LinkedList;
import java.util.Collections;
import java.util.List;
/**
* Copyright (c), AnkitMittal JavaMadeSoEasy.com
*/
public class LinkedListSynchronizedExample {
   public static void main(String args[]) {
          List<String> linkedList = new LinkedList<String>();
          linkedList.add("ankit");
          linkedList.add("javaMadeSoEasy");
          // getting synchronized LinkedList
          List<String> synchronizedList = Collections.synchronizedList(linkedList);
         
          // 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 :