exception - ConcurrentModificationException in spite of using Iterator -
i using following class:
public class ticker implements runnable { private linkedlist<timeable> timeables = new linkedlist<>(); @override public void run() { listiterator<timeable> = timeables.listiterator(); while (it.hasnext()) { it.next().tick(); } } public void add(timeable timeable) { timeables.add(timeable); } public void remove(timeable timeable) { timeables.remove(timeable); }
}
i thought iterators prevent concurrentmodificationexception throws 1 @ "it.next().tick();".
how can solve this?
the java collection classes fail-fast, linkedlist
throw concurrentmodificationexception
if structure modified 1 thread while thread in process of iterating on elements.
for multithreaded code should use thread safe collection such copyonwritearraylist
(which provides fail safe iterator of collection @ point in time) or concurrentlinkeddeque
(if need access first or last element).
Comments
Post a Comment