Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GWT app getting java.util.ConcurrentModificationException from MVC pattern

Tags:

gwt

I am getting this error everytime my Observers are traversed.

@Override
public void notifyObservers(ModelViewInterface model) {
    for(Observer<ModelViewInterface> o : this.observers)
        o.notify(model);
}

GWT does not have threads, so it is not a synchronization issue.

It seems to happen after I press a button, any ideas of how to avoid this error?

like image 990
jax Avatar asked Nov 27 '10 13:11

jax


People also ask

How do I fix Java Util ConcurrentModificationException?

How do you fix Java's ConcurrentModificationException? There are two basic approaches: Do not make any changes to a collection while an Iterator loops through it. If you can't stop the underlying collection from being modified during iteration, create a clone of the target data structure and iterate through the clone.

What causes Java Util ConcurrentModificationException?

What Causes ConcurrentModificationException. The ConcurrentModificationException generally occurs when working with Java Collections. The Collection classes in Java are very fail-fast and if they are attempted to be modified while a thread is iterating over it, a ConcurrentModificationException is thrown.

How do I stop Concurrentmodification exception?

Using Loops: We used the Iterator remove() method instead of that we can use a for loop to avoid ConcurrentModificationException in a Single-threaded environment. If we add any extra objects then we can ensure that our code takes care of them.


1 Answers

From the javadoc of ConcurrentModificationException:

Note that this exception does not always indicate that an object has been concurrently modified by a different thread. If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception.

So in your case, it seems that o.notify(model) modifies this.observers - directly or indirectly. This is a common phenomenon when modifying the collection you're iterating over.

To avoid concurrent modification, you can operate on a copy of the collection like this:

for(Observer<ModelViewInterface> o : 
           new ArrayList<ModelViewInterface>(this.observers)) {

    o.notify(model);
}

However, sometimes this is not what you want - the current behaviour of o.notify could also indicate a bug.

like image 71
Chris Lercher Avatar answered Sep 20 '22 12:09

Chris Lercher