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
?
Yes, it will make it safe from ConcurrentModificationException
at the expense of everything essentially being single-threaded.
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.
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());
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With