3

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.

Matt Fenwick
  • 48,199
  • 22
  • 128
  • 192
Rama
  • 4,697
  • 5
  • 22
  • 19

2 Answers2

6

Check out java.util.concurrent, it has what you're looking for.

Matt Fenwick
  • 48,199
  • 22
  • 128
  • 192
  • 1
    Remember to link current documentation – Hunter McMillen Nov 25 '11 at 23:04
  • @HunterMcmillen -- thanks for the heads-up, fixed now. (1.7 is the current one, right?) – Matt Fenwick Nov 25 '11 at 23:06
  • 3
    `ConcurrentModificationException` doesn't necessarily have anything to do with *thread-based concurrency*; it's easy enough to provoke in a program accessing the collections on only one thread. While it's true that the collections that address the OP's problem lie within the package you mention, I think more explanation of the underlying problem is due. – seh Nov 25 '11 at 23:35
4

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.

Anthony Accioly
  • 21,918
  • 9
  • 70
  • 118