简体   繁体   中英

How does HashMap.computeIfAbsent fail under multithreaded use?

The documentation for java.util.HashMap clearly states: "If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally."

However, consider the use case where you using the map as a cache to reduce immutable object creation, where only computeIfAbsent is called on the HashMap (no removal/eviction). And the only thing you care about is that computeIfAbsent return a valid object; you don't care if computeIfAbsent occasionally produces extra objects or overwrites an existing entry.

What is the worst that could happen? In my casual testing there are no negative consequences. (I'd use ConcurrentHashMap, but it is relatively slow in this use case.)

The problem here: if at all, that thread safety would be an implementation detail. It could happen to work out for one JVM version, but be slightly different, or "off" in some other version of java.util.HashMap.

Quoting another answer :

That being said, the most commonly used Map implementations, specifically HashMap are not thread safe. Adding elements from different threads can leave the map in an inconsistent state where eg elements that have been inserted cannot be retrieved though size() shows that they're present.

In other words: even if you don't have a problem today, just switching to a different java version could theoretically open up your design to fail.

Keep in mind: the only guarantee you have is the Map interface. You are using a container that has some internal structure that gets updated by multiple threads. If that happens to not cause inconsistencies then that is pure coincidence .

If reading and writing to HashMap would "just work" in multithreaded settings, why would ConcurrentHashMap be required in the first place?!

What is the worst that could happen?

How about, Thread A is in a computeIfAbsent(k1,...) call while thread B is simultaneously in get(k2), and the get(k2) returns a wrong value?

I don't know if that's the worst that could happen, but it's definitely something that could happen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM