Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Like most of these, that's part of Map in general.


The thread-safe implementation of computeIfAbsent in ConcurrentHashMap is the real improvement. "computeIfAbsent" on a non-concurrent Map is merely syntactic sugar.


FWIW, 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
        }
    }


Neither 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.


Default 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".


Default Java 8 Map implementation is merely

Worth noting that's not actually the HashMap implementation.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: