Wednesday, January 9, 2013

Collections Interview Questions

1) How to make an ArrayList synchronized?

ArrayList is not synchronized by default, it can be synchronized by creating a SynchronizedList out of the original list.
List list = new ArrayList();

List syncList = Collections.synchronizedList(list);


Remember that the iterator on the newly synchronizedList is not synchronized, need to synchronize on the list object before accessing the elements in  a multi-threaded environment, otherwise it may result in non deterministic behaviour.

All operations must happen to the backing list through the SynchronizedList.

synchronized(syncList) {
    Iterator it = syncList.iterator();
   while(it.hasNext()) {
    System.out.println(it.next());  
}
}


There is another alternative, which does create a new copy of the underlying Array each time when you use mutator(add)  methods is CopyOnWriteArrayList(Collection c) . It will throw ConcurrentModificationException.

No comments:

Post a Comment