• Post Reply Bookmark Topic Watch Topic
  • New Topic

Two strange exception while working with collections concurrently.

 
Dmitry Zhuravlev
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
java.lang.ArrayIndexOutOfBoundsException: 200
at java.util.ArrayList.add(Unknown Source)
at solutiondatabase.CollectionGamesExample$MyThread.run(CollectionGamesExample.java:19)




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
Posts: 67
Debian Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ArrayList is not thread safe; that might be your problem. Try to replace the ArrayList with a Vector.
 
Henry Wong
author
Sheriff
Posts: 22528
109
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Aditya Jha
Ranch Hand
Posts: 227
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 227
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Copy-pasting has never benefitted me... please read 'ConcurrencyModificationException' as 'ConcurrentModificationException'.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!