Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over synchronized collection

I asked here a question about iterating over a Vector, and I have been answered with some good solutions. But I read about another simpler way to do it. I would like to know if it is good solution.

synchronized(mapItems) {
    Iterator<MapItem> iterator = mapItems.iterator();
    while(iterator.hasNext())
        iterator.next().draw(g);
}

mapItems is a synchronized collection: Vector. Is that make the iterating over the Vector safe from ConcurrentModificationException?

like image 306
Shelef Avatar asked Mar 15 '13 17:03

Shelef


4 Answers

Yes, it will make it safe from ConcurrentModificationException at the expense of everything essentially being single-threaded.

like image 110
Alexander Pogrebnyak Avatar answered Oct 27 '22 22:10

Alexander Pogrebnyak


Yes, I believe that this will prevent a ConcurrentModificationException. You are synchronizing on the Vector. All methods on Vector that modify it are also synchronized, which means that they would also lock on that same object. So no other thread could change the Vector while you're iterating over it.

Also, you are not modifying the Vector yourself while you're iterating over it.

like image 28
rgettman Avatar answered Oct 27 '22 22:10

rgettman


Simply synchronizing the entire collection would not prevent a ConcurrentModificationException. This will still throw a CME

synchronized(mapItems) {
   for(MapItem item : mapsItems){
      mapItems.add(new MapItem());
   }
}
like image 29
John Vint Avatar answered Oct 27 '22 20:10

John Vint


You may want to consider using a ReadWriteLock.

For processes which iterate over the list without modifying its contents, get a read lock on the shared ReentrantReadWriteLock. This allows multiple threads to have read access to the lock.

For processes which will modify the list, acquire the write lock on the shared lock. This will prevent all other threads from accessing the list (even read-only) until you release the write lock.

like image 27
Sam Barnum Avatar answered Oct 27 '22 20:10

Sam Barnum