Reputation: 4767
I'm making a game in Java. Every enemy in the game is a thread and they are constantly looping through the game's data structures (I always use the class Vector).
Lately I have been getting the "ConcurrentModificationException" because an element is being added/removed from a Vector while a Thread is looping through it. I know there are strategies to avoid the add/remove problem (I actually use some to avoid problems with Removes but I still have problems with "Adds").
I heard that java supports a Vector/List that avoids the ConcurrentModificationException.
Do you have any idea of what this structure might be? Thanks.
Upvotes: 3
Views: 1727
Reputation: 22471
CopyOnWriteArrayList. But read its javadocs carefully and consider if in practice it gives the behavior that you are expecting (check Memory Consistence effects), plus if the performance overhead is worth it. Besides synchronization with ReentrantReadWriteLock, AtomicReferences, and Collections.synchronizedList may help you.
Upvotes: 4
Reputation: 49105
Check out java.util.concurrent, it has what you're looking for.
Upvotes: 6