4

I have no idea why a ConcurrentModificationException occurs when i iterate over an ArrayList. The ArrayList is methode scoped, so it should not be visible by other threads which execute the same code. At least if i understodd multi threading and variable scopes correctly.

Caused by: java.util.ConcurrentModificationException
at java.util.AbstractList$SimpleListIterator.next(AbstractList.java:64)
at com....StrategyHandler.applyStrategy(StrategyHandler.java:184)

private List<Order> applyStrategy(StorageObjectTree storageObjectTree) {
    ...
    List<OrderHeader> finalList = new ArrayList<Order>();

    for (StorageObject storageObject : storageObjectTree.getStorageObjects()) {

        List<Order> currentOrders = strategy.process(storageObject);
        ...
        if (currentOrders != null) {
          Iterator<Order> iterator = currentOrders.iterator();
          while (iterator.hasNext()) {
            Order order = (Order) iterator.next();     // line 64
            // read some values from order
          }

          finalList.addAll(currentOrders);
        }
    }

    return finalList;
}

Can anybody give me an hint what could be the source of the problem?

Joysn
  • 987
  • 1
  • 16
  • 30
  • don't cast the iterator.next() to Order – newbieee Jun 30 '14 at 07:57
  • 4
    @newbieee: While the cast is unnecessary, it's not the cause of the problem. – Jon Skeet Jun 30 '14 at 07:57
  • 1
    You´re not adding or deleting any value of currentOrders right? – paul Jun 30 '14 at 07:57
  • 1
    you need to paste more code here ,somewhere you are modifying currentOrders. – Vipin Jun 30 '14 at 07:57
  • There must be somewhere before calling iterator.next() where you are modifying the list/ post at least everywhere you are processing the list – maress Jun 30 '14 at 07:58
  • the problem is that if you modify the collection while being iterated, it throws that exception. Sure the List is scoped in the method, but that doesnt mean another thread cant access it the same way. So im guessing you are modifying the collection in another thread. – Ed Morales Jun 30 '14 at 07:58
  • 2
    Do you have any other threads that may be accessing the currentOrders list returned by the strategy.process() method? – pillingworth Jun 30 '14 at 07:58
  • What kind of list is returned by strategy.process? Is it a plain ArrayList ore some specialized Collection? – mschenk74 Jun 30 '14 at 08:00
  • 2
    Try copying into an ArrayList before iterating - not a solution but may help locate the problem `List currentOrders = new ArrayList<>(strategy.process(storageObject));` – pillingworth Jun 30 '14 at 08:12
  • @paul no, the list is just iterated, and some getters are called on the objects of that list – Joysn Jun 30 '14 at 12:16
  • @EdwardM.B. hm. how is it possible that another thread can access that list? – Joysn Jun 30 '14 at 12:17
  • The strategy.process() returns a reference to a list. If the same list reference is returned to other threads then you are likely to get problems. – pillingworth Jun 30 '14 at 12:21
  • @pauli the list created by strategy.process(storageObject) is added to another list using finalList.addAll(currentOrders). I adapt the code in the posting ... – Joysn Jun 30 '14 at 12:24
  • @pauli no, as that list is not returned, directly, its elements are added to another list, and that final list is returned. and no other thread is accessing that list. Or, at least i am not aware of it because that list is not cached anywhere. The caller jost logs some stuff about that list, post the entities to the database and the execution thread is finished... – Joysn Jun 30 '14 at 12:28
  • @mschenk74 the returned list is an java.util.ArrayList – Joysn Jun 30 '14 at 12:29

4 Answers4

2

If You have read the Java Doc for ConcurrentModifcationException :

It clearly states the condition in which it occurs:

This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible. For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances. Some Iterator implementations (including those of all the general purpose collection implementations provided by the JRE) may choose to throw this exception if this behavior is detected. Iterators that do this are known as fail-fast iterators, as they fail quickly and cleanly, rather that risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Note that this exception does not always indicate that an object has been concurrently modified by a different thread. If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception.

Note that fail-fast behavior cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast operations throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: ConcurrentModificationException should be used only to detect bugs.

In your case as you said, you do not have multiple threads accessing this list. it might still be possible as per second paragraph above if your single thread that is reading from iterator might be trying to write to it as well.

Hope this helps.

Sanjeev
  • 9,876
  • 2
  • 22
  • 33
0

This exception occurred when you changing/adding/removing values from your list and in the same time you are iterating it. And if you use many threads at the same time...

Try to surround your if by synchronized(currentOrders) { /* YOUR LAST CODE */ }. I'm not sure of this but try it.

0

Depending on the implementation of strategy.process(..) it could be that this implementation has still a reference to the List it passed back as a result. If there are multiple Threads involved in this implementation it might be possible that the List is modified by one of these threads even after it is passed back as a result. (If you know the "Future" pattern, you could perhaps imagine an implementation where a method immediately returns an empty List and adds the actual results later using another Thread)

You could try to create a new ArrayList "around" the result list and iterate over this copied list.

mschenk74
  • 3,561
  • 1
  • 21
  • 34
0

You might want to read this SO post. Basically switch and use CopyOnWriteArrayList if you can't see where the problem is coming from.

Community
  • 1
  • 1
Bwire
  • 1,181
  • 1
  • 14
  • 25