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, I believe that this will prevent a
ConcurrentModificationException
. You are synchronizing on theVector
. All methods onVector
that modify it are alsosynchronized
, which means that they would also lock on that same object. So no other thread could change theVector
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
YES It makes the iterating over Vector safe from
ConcurrentModificationException
.If it is not synchronized then in that case , if you are accessing the Vector via various threads and some other Thread is structurally modifying the Vector at any time after the iterator is created , the iterator will throwConcurrentModificationException
. Consider running this code:At my system it is showing following output while execution:
But on the other hand if you make the block of code containing
Iterator
to access thatVector
synchronized usingmapItems
as lock , it will prevent the execution of other methods related toVector
until thatsynchronized
block is completed atomically .Yes, it will make it safe from
ConcurrentModificationException
at the expense of everything essentially being single-threaded.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 we invoke add method inside while loop then throws exception.