I’m trying to write a game engine, in which a list of list of sprites is used to hold all sprites (The list of lists lets me order the sprites in a sensible manner). The problem is, I need to repeatedly add and remove sprites, something that violates the fail-fast iterators pretty quickly, giving me a concurrent modification exception. Can I have multiple iterators on a list, and will this stop the exceptions? Failing this, is there a way to ‘release’ a list’s iterator, so that the list no longer checks for modifications?
Share
Yes you can, and no it won’t. (The iterator checks the state of the list to determine if a concurrent modification has occurred.)
No there isn’t, at least not with the standard list classes. And it would be a bad idea because it would be likely to lead to the kind of anomalies and data corruptions that fail-fast iterators are designed to avoid. (Would you prefer your application to fail predictably with a ConcurrentModificationException, or fail occasionally with random data structure corruptions and/or weird exceptions?)
I think you need to look at alternative List implementation class in which the iterators allow concurrent modifications. Depending on how your application is using the list, the possibilities include:
CopyOnWriteArrayListthis has full list semantics, but write operations tend to be a bit expensive.ConcurrentLinkedDequethis most of the operations you’d expect on a list (but not positional insert or remove), and write operations are cheaper.In both cases, the iterators provide weaker guarantees about whether or not the iteration will see all elements. You need to read the respective javadocs carefully to be sure that the semantics are suitable.
With a couple of historical exceptions, the collection types in
java.utilare not designed for concurrent / multi-threaded use cases. If your application requires collection types that are accessed by multiple threads, you need to look at the implementations in thejava.util.concurrentpackage.