问题
So I was combing through some logs from our web server the other day (looking for something else), when something peculiar caught my eye.
java.lang.IndexOutOfBoundsException: Index: 15, Size: 19
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
This seemed impossible to me.
I looked up the source code for ArrayList#rangeCheck and it blew my mind
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
Based on the the message that I received should never have happened.
Unfortunately I don't know what the contents were exactly at this time (this is called from code that's used for a lot of things). And I have been unable to reproduce it. I don't even know where I'd start.
The question: Should this be able to happen? Is this a glitch in Java? Or just a freak accident.
I recognize that this may be off topic. I wish I had more information about what happened, but I don't.
回答1:
ArrayList is not multithread safe. If it were being modified by one thread at about the time of an access by another thread, index >= size
could have been true when the test was run, but false by the time the message was built.
回答2:
Should this be able to happen? Is this a glitch in Java? Or just a freak accident.
All the above.
Let us image you are adding to the ArrayList in one thread and accessing it in another.
Lets say you have a size of 14, but you access index 15
T1: if (index >= size) // is true
T2: for(int i=0;i<5;i++) list.add(N); // so now we have 19.
T1: outOfBoundsMsg(index); // Index: 15, Size: 19
来源:https://stackoverflow.com/questions/24943122/indexoutofboundsexception-index-15-size-19