3 ms·
The thread-safe implementation of computeIfAbsent in ConcurrentHashMap is the real improvement. "computeIfAbsent" on a non-concurrent Map is merely syntactic su
by astral303 10y ago
The thread-safe implementation of computeIfAbsent in ConcurrentHashMap is the real improvement. "computeIfAbsent" on a non-concurrent Map is merely syntactic sugar.
- pvg 10y agoNeither is 'merely syntactic sugar', take a look at their respective implementations. It's hardly surprising that a method on a class named 'ConcurrentHashMap' in 'java.util.concurrent' provides certain concurrency-related guarantees. It's the point of the whole thing and is written on the tin.
- astral303 10y agoDefault Java 8 Map implementation is merely: "get X. if X absent, compute for X, put X." These lines of code have been written over and over again for anyone using a Map in Java, no doubt. It is entirely trivial and almost impossible to get wrong writing it out on your own. Whereas writing a performant concurrent "computeIfAbsent" is extremely non-trivial and if you try to do it yourself, you have a high chance of getting it wrong or slow. Therefore, CHM "computeIfAbsent" is new and exciting, and Map "computeIfAbsent" is "could care less".
- pvg 10y agoDefault Java 8 Map implementation is merely Worth noting that's not actually the HashMap implementation.
- brown9-2 10y agoFWIW, there has been a thread-safe implementation of putIfAbsent(K, V) since ConcurrentMap was introduced in 1.5. computeIfAbsent just adds the additional property of avoiding possibly computing the value more than once if there is a race in if (!map.containsKey(key)) { V value = compute(key); V existing = map.putIfAbsent(key, value); if (existing != null) { // someone else won the race } }