• Post Reply Bookmark Topic Watch Topic
  • New Topic

Multithreading Dilemna  RSS feed

 
Surinder Mehra
Ranch Hand
Posts: 44
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Below code throw outofBound Exception on arraylist if executed continuously(immediately)2-3 times.
I am aware that this exception can be avoided by synchronizing alterlist() methods or synchronized bocks using different objectslock1 and lock2 I have created. I want to understand why this exception is thrown. Arraylist auto increase its size when needed.

Can anyone explain what is happening behind the scene







Exception:

Starting...
Exception in thread "Thread-1" java.lang.ArrayIndexOutOfBoundsException: 25
at java.util.ArrayList.add(ArrayList.java:352)
at com.suri.threads.MultipleLocks.alterList2(MultipleLocks.java:75)
at com.suri.threads.MultipleLocks.process(MultipleLocks.java:56)
at com.suri.threads.MultipleLocks$2.run(MultipleLocks.java:36)
at java.lang.Thread.run(Thread.java:662)
Time taken : 2067
List 1 size : 1013 List 2 Size : 1013
 
Henry Wong
author
Sheriff
Posts: 23280
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

The ranch office forum is used for discussions regarding the ranch itself ... let's move this topic to a more appropriate forum.

Henry
 
Henry Wong
author
Sheriff
Posts: 23280
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Surinder Mehra wrote:
Can anyone explain what is happening behind the scene


The behavior of using classes in a non-thread-safe manner is completely undefined, so, I would argue that it is probably better to just *not* do that, than to figure out how broken code is behaving. Regardless...

Surinder Mehra wrote:
I am aware that this exception can be avoided by synchronizing alterlist() methods or synchronized bocks using different objectslock1 and lock2 I have created. I want to understand why this exception is thrown. Arraylist auto increase its size when needed.


A quick look at the code shows that the add() method checks if there is enough room, increases it if there isn't, and then add the element. So, if there is room for one more element, we can speculate that the two threads checks and both confirm that there is enough room for its one element. The first thread then adds and complete successfully, and the second fails.

In my opinion, I am surprised you didn't get something more complicated. It could be possible to corrupt data structures, and you could wind up with all sorts of other errors.

Henry
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!