Should HashMap::computeIfAbsent be considered a "structural modification" for an existing key?

Peter Levart peter.levart at gmail.com
Tue Nov 20 11:19:05 UTC 2018


Ah, I see your point. Haven't read this part of your message below 
before. You don't know in the MultiMap code whether the key is already 
in the HashMap or not (so you can't choose .get() vs. 
.computeIfAbsent()), but  the user of the MultiMap might expect that 
when the MultiMap has been pre-initialized, that MultiMap.get() will 
only be a read operation and therefore thread-safe.

 From consistency point of view HashMap might be expected to not modify 
its internal state when it's obvious that the external view of its state 
doesn't change. .computeIfAbsent() is violating that expectation. 
WeakHashMap is violating that expectation too, but it has its own 
reasons while HashMap doesn't have them...

I  think this could be fixed.

Regards, Peter

On 11/20/18 12:52 AM, Michael Rasmussen wrote:
> From: Andrew Dinn <adinn at redhat.com>
>> I have to ask the obvious: Why does the question matter?
> I'm trying to figure out if something is a bug in HashMap in the JDK, or in Weld :D
>
> The case in question is basically, a HashMap is created, and then the keys are iterated over concurrently.
> The issue here though is that the HashMap is used as the backing of a MultiMap, and the multimap.get is basically hashmap.computeIfAbsent(key, k -> new HashSet()).
> Meaning you have a HashMap, which you've fully initialized, and you're iterating over all the known keys in the map... but surprisingly the call to .get actually changes the structure of the map, leading to bad consequences.
>
> /Michael



More information about the core-libs-dev mailing list