Thursday, November 02, 2006

Using Collections.synchronizedList

Till yesterday i was thinking that if i use a Collections.synchronizedList () and use that returned list , i need not synchronize that list. But after running my app i found that i was getting the ConcurrentModificationException which encouraged me to look at the java api ocs and then i found out that my conception was entirely wrong as can be seen from the exceprt below



It is imperative that the user manually synchronize on the returned list when iterating over it:
List list = Collections.synchronizedList(new ArrayList());
...
synchronized(list) {
Iterator i = list.iterator(); // Must be in synchronized block
while (i.hasNext())
foo(i.next());
}
Failure to follow this advice may result in non-deterministic behavior.

Seeing the above docs i was confused as to what is the usage of the synchronizedList??
If we are anyways synchronizing it externally then we can as well use the normal list and
synchronize it rather than using the synchronized list.I stilll have to find out the reason for this
can anyone put some light on me regarding this?