Monday, 12 February 2018

Why ConcurrentHashMap does not allow null keys and null values ?

nulls aren't allowed in ConcurrentMaps (ConcurrentHashMaps, ConcurrentSkipListMaps) is that 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.

In simple words, 

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

The code is like this : 
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). 

No comments:

Post a Comment