Reputation: 563
I was in the middle of making a game for my final when I noticed that I randomly get the Exception when I call repaint();
The cause of it all was that different objects updated at different times and had their own Thread
to update themselves. Occasionally, an entity would update itself while it is being painted. The painting thread runs at about 60-100 FPS, while the entities update at about once every 300 ms.
The game does not halt or have any other issues, related to this.
I know it's a bad idea to ignore it, but is there anything else I can do? Have multiple threads is the only solution I could think of to make the game work.
Thanks for reading!
Edit: The issue seems to happen when I try to remove an entity while i'm painting; both use the same List.
Upvotes: 2
Views: 1624
Reputation: 691655
The main problem with multi-threading is precisely to make sure that, although the state of objects is shared between several threads, this state always stays consistent. This is why synchronized blocks exists, why locks exist, why volatile variables exist.
Just ignoring this problem and hope no serious problem will occur is a recipe to disaster. Everything will run fine for 1 hour, and then you'll start getting exceptions everywhere, false results, etc.
The fact that you let two threads access the same non-thread-safe list concurrently shows that your code is buggy. It's plain incorrect and should definitely be fixed.
You should synchronize the accesses to your shared list. Read tutorials and books about concurrency in Java, because synchronization is not an option when multiple threads are running.
Upvotes: 1
Reputation: 108962
A ConcurrentModificationException has nothing to do with multi-threading (although multiple threads could be involved). It occurs when you are iterating over a collection (eg a List
) while items are being added or removed from the collection through means other than the Iterator.remove()
method.
This could happen on a different Thread, but it could be the same thread. For example this piece of code will also throw a ConcurrentModificationException:
Iterator iter = someList.iterator();
while(iter.hasNext()) {
Object item = iter.next();
someList.remove(item);
}
If instead iter.remove()
had been called the error would not have occurred.
Ways to avoid this:
remove()
method of the iteratorCopyOnWriteArrayList
which avoid this error at the expense of creating a copy of the internal array on each change.Upvotes: 6