Tuesday, 3 November 2015

Why ConcurrentHashMap does not allow null keys and null values?

ConcurrentHashMap does not allow null keys and null values

According to Doug lea (author of the ConcurrentHashMap)

The main reason that nulls aren't allowed in ConcurrentMaps (ConcurrentHashMaps, ConcurrentSkipListMaps) because there will be ambiguities that may be just barely tolerable in non-concurrent maps can't be accommodated.

The main one is that if map.get(key) returns null, you can't detect whether the key explicitly maps to null vs the key isn't mapped.

In a non-concurrent map, you can check this via map.contains(key), but in a concurrent one, the map might have changed between calls.

The code is like this :

    
if (map.containsKey(k)) {
     return map.get(k);
} else {
     throw new KeyNotPresentException();
}

It might be possible that key k might be deleted in between the get(k) and containsKey(k) calls.

As a result, the code will return null as opposed to KeyNotPresentException (Expected Result if key is not present).

The Null key and value allowed in HashMap because there is no Concurrent access.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...