| Author |
Two strange exception while working with collections concurrently.
|
Dmitry Zhuravlev
Ranch Hand
Joined: Apr 14, 2010
Posts: 90
|
|
Guys,
please provide me with some explanations concerning WHY I get this exceptions.
(1) Several similair threads modify the same arraylist concurrently. No synchronization provided. I receive the message:
Why? add can throw IndexOutOfBounds, but only if I make add(index, Object) where index > list.size(). But here I just add elements to the end of the list!
(2) This code results in ConcurrencyModificationException:
Why? I even dont have several threads here! Or may be its not about concurrency and the Exception name is misleading in this case?
|
 |
Mike Peters
Ranch Hand
Joined: Oct 10, 2009
Posts: 67
|
|
|
ArrayList is not thread safe; that might be your problem. Try to replace the ArrayList with a Vector.
|
Mike Peters
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16695
|
|
Mike Peters wrote:ArrayList is not thread safe; that might be your problem. Try to replace the ArrayList with a Vector.
Or wrap the ArrayList with a list from Collections.synchronizedList().
Henry
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
Aditya Jha
Ranch Hand
Joined: Aug 25, 2003
Posts: 227
|
|
1) If you check the source code of class ArrayList, the add method is implemented as:
Notice the 3rd line, where an array element is assigned the given value 'e'. Your ArrayIndexOutOfBoundsException is thorwn from this line (notice the exception is not collections' IndexOutOfBoundsException). Due to parallel working of threads (and no synchronization), size may become an invalid index for the array 'elementData'.
2) ConcurrencyModificationException can happen in a single-thread scenario also. When you iterate over a collection using an Iterator (or, the new for-each loop, as it uses the same), and the collection is modified in between of the iteration. The way to do this would be to use Iterator.remove() method:
|
 |
Aditya Jha
Ranch Hand
Joined: Aug 25, 2003
Posts: 227
|
|
Copy-pasting has never benefitted me... please read 'ConcurrencyModificationException' as 'ConcurrentModificationException'.
|
 |
 |
|
|
subject: Two strange exception while working with collections concurrently.
|
|
|