Thursday, January 3, 2008

How to avoid ConcurrentModificationException?

java.util.ConcurrentModificationException is a kind of runtime exception that happens when a thread iterates a vector while another thread changes the element of vector, either add or remove element. This exception encountered mostly at multithreaded application.
To avoid this exception, simply add synchronized keyword to the methods that access the vector. This will guarantee that only one thread can access the vector at a time.


Example:

class Collections {
private Vector collection = new Vector();

synchronized void displayElement(){
Iterator it = collection.iterator();
while (it.hasNext()){
System.out.println((String)it.next());
}
}

synchronized String removeElement(int index) throws Exception {
return (String) collection.remove(index);
}

synchronized boolean addElement(String element) throws Exception {
return collection.add(element);
}
}



Please note that adding synchronized keyword will decrease the performance, especially for realtime application. So be carefull.

1 comment:

Unknown said...

Putting one question: Why r u put wait() notify(0 and notifyall() method in Object Class but these method used in Thread Class