ArrayIndexOutOfBoundsException in HashMap
I have a strange exception (from bugsense) that can’t be reproduced:
java.lang.ArrayIndexOutOfBoundsException: length=0; index=1
at java.util.HashMap.addNewEntry(HashMap.java:476)
at java.util.HashMap.put(HashMap.java:408)
Why does the put method on ConcurrentHashMap
throw ArrayIndexOutOfBoundsException
?
(I’ve also tried using ConcurrentHashMap without any luck)
Any ideas?
Edit:
Add code:
final Map<String, DataSource> dataSources = new ConcurrentHashMap<String, DataSource>();
public void setDataSource(@Nonnull String field, @Nullable DataSource source) {
concurrent hash map doesnt allow null values
if (field != null) {
if (source != null) {
dataSources.put(field, source);
} else {
dataSources.remove(field);
}
}
}
Multiple threads call this method at the same time
Thank you.
Solution
The stack trace shows that you are using the Android version of HashMap .
My diagnosis is that you somehow managed to get a corrupted HashMap
object. The addNewEntry
method is indexing the main hash array (table
), but the length of the array is (obviously) zero. This is something that should never happen… And (I think) it only happens if the capacity calculation goes wrong when scaling the array. (Check how the code handles empty maps…).
Probably (I guess) you’re getting an error in the HashMap
implementation in the version of Android you’re using. However, I think the corruption is more likely due to your application using multithreaded use/updating map objects without proper synchronization. I recommend that you explore the theory first; That is, check your synchronization.
I don’t know why the issue with the update is talking about ConcurrentHashMap
. The evidence in the stack trace clearly indicates that something is wrong with HashMap
. I am only prepared to provide a diagnosis based on the actual evidence I can see.