Monday, December 13, 2010

Not Only Iterating

In many cases we have to iterate through collections as an example we have to display some data table
in that case we pull data as collection and use iterator(or any other iteration mechanism such as for each loop,enumerations) to traverse
through it. Those iterators are very much handy if we just need to display or visit that item but in real world applications we are  not limited with that viewing part we may need to modify the collection as well
the problem   accrues when we need to do such a things.Assume we need to remove some of the elements from the collection while we are visiting each.
example



basically for -each loops and Enumerations are not allowing modifications to the collection if we use those loops as above example in many cases(@see notes) it throws a common exception called ConcurrentModificationException
this is a common mistake and it can happen in many ways follow  are some cases that this exception may encounter.
1.In multi threaded programming accessing the same collection by two or more   threads
2.In normal scenarios modifying the iterator while it's being iterate.

Avoiding the exception 

for-each loop cannot save us from here so we have to look back with our previous savior Iterator.Iterator object have few functions to modify the collection while iterate.





this will save us from that exceptions if you search through the Google you may come up with this kind of solution.But we have changed our attitude not to use Iterator so we have to find a solution with our for-each loop.
here is the simple solution and we are still stick to the for each :D and this is more safer(@see notes) than using Iterator


notes:
many cases
this exception may not be thrown in some cases and its is depend on the architecture that you are using
if you using struts this exception may not be accours because struts is based on singleton design pattern and there are no multithreaded scenario in struts(STRUTS issue a copy to every one so no need to worry of issues related to multithreaded environment)

more safer
keep in mind to use thread safe collection or make the collection thread safe explicitly for “toBeRemoved” collection
@see how to make a set thread safe explicitly