Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayIndexOutOfBoundsException in HashMap

I have a weird exception that I cannot reproduce (come from bugsense):

java.lang.ArrayIndexOutOfBoundsException: length=0; index=1
at java.util.HashMap.addNewEntry(HashMap.java:476)
at java.util.HashMap.put(HashMap.java:408)

How come put method on ConcurrentHashMap can throw ArrayIndexOutOfBoundsException ? (I tried also to use ConcurrentHashMap but without any luck)

any ideas?

EDIT:

Adding 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);
        }
    }
}

Many threads call this method simultaneously

Thanks.

like image 386
idog Avatar asked Jul 12 '26 12:07

idog


1 Answers

The stacktrace show that you are using the Android version of HashMap.

My diagnosis is that you've somehow managed to get a corrupt HashMap object. The addNewEntry method is indexing the main hash array (table), but the length of the array is (apparently) zero. This is something that should never happen ... and (I think) it can only happen if the capacity calculation goes wrong when expanding the array. (Check how the code handles an empty map ...)

It is possible (I guess) that you've encountered a bug in the HashMap implementation in the version of Android you are using. However I think it is far more likely that the corruption is due to your application using / updating the map object using multiple threads without proper synchronization. I recommend that you explore that theory first; i.e. check your synchronization.


I don't know why the updated question is talking about ConcurrentHashMap. The evidence in stacktrace clearly shows that the problem occurred with HashMap. I'm only prepared to offer a diagnosis based on actual evidence that I can see.

like image 158
Stephen C Avatar answered Jul 14 '26 00:07

Stephen C