1

I have read many articles but unable to understand the reason why Concurrent hash map does not allow null key or null values. Some articles gives this explanation:

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

Since m is a concurrent map, key k may be deleted between the containsKey and get calls, causing this snippet to return a null that was never in the table, rather than the desired KeyNotPresentException.

But, same would be the case with not-null key. Can anyone please explain the reason for the same.

ForguesR
  • 3,558
  • 1
  • 17
  • 39
Gaurav Seth
  • 186
  • 3
  • 11
  • 2
    Possible duplicate of [Why does ConcurrentHashMap prevent null keys and values?](http://stackoverflow.com/questions/698638/why-does-concurrenthashmap-prevent-null-keys-and-values) –  Dec 10 '15 at 18:40
  • I am talking about java. I didn't get your point – Gaurav Seth Dec 10 '15 at 18:41
  • duplicate of https://stackoverflow.com/questions/698638/why-does-concurrenthashmap-prevent-null-keys-and-values – Pradeep Singh Jun 21 '17 at 10:33
  • https://stackoverflow.com/users/6340192/pradeep-singh This isn't actually a duplicate. The answers of that linked question only provide explanation for values part. No one provided any justification properly for keys part. While detailing the question, Gaurav especially pointed out this. Please read it fully before marking/commenting this as duplicate. – Vicky Oct 06 '20 at 08:56

1 Answers1

0

The main reason that 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. ... get(key) returns null , you can't detect whether the key explicitly maps to null vs the key isn't mapped.

new coder
  • 41
  • 2