Re: Yet another ConcurrentModificationException question
Andy Chambers wrote:
Hi folks,
Apologies for asking about this FAQ. I have looked up the relevant
java tutorial but I just want to check my understanding with the
following example.
Iterator oIterator = m_oCollection.iterator();
while( oIterator.hasNext()) {
Element oElement = (Element)oIterator.next();
String sOIDValue =
oElement.getAttribute(oElement.getOIDKey());
if( sOIDValue != null && sOIDValue.equals(sElementOID) ) {
// We have a match
return oElement;
}
}
If I know that neither getAttribute() or getOIDKey() can alter the
"structure" of m_oCollection, is it true to say that a
ConcurrentModificationException thrown from within the body of the
while loop above, *must* have been caused by another thread altering
the structure of m_oCollection?
No: Six methods are called, and you've only ruled out two
of them as possible collection modifiers. But if you also posit
no modifications from the other four methods, then I think
you're right.
So to prevent this from happening, I can make m_oCollection a
synchronized Vector (currently it is just a normal vector), and put
this while loop inside a synchronized block.
First, the methods of a "normal" java.util.Vector are
already synchronized on the Vector itself. (The Javadoc
says only that "Vector is synchronized," which leaves too
many questions unanswered for my taste, but you can always
read Vector's source if you need a more precise answer.)
Second, it is not enough to synchronize just the loop:
the synchronization must also cover the obtaining of the
Iterator. Otherwise, you could have
T1: synchronize, get Iterator, desynchronize
T2: synchronize, modify Vector, desynchronize
T1: synchronize, call Iterator's method, boom!
--
Eric Sosman
esosman@ieee-dot-org.invalid