Over a million developers have joined DZone.

Puzzler: Nested computeIfAbsent

· Java Zone

Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code! Brought to you in partnership with ZeroTurnaround.

The Java 8 libraries have a new method on map, computeIfAbsent.  This is very useful way to turn your Map into a cache of objects associated with a key.

However, there is a combination you might not have considered; what happens if you call computeIfAbsent inside itself.

map.computeIfAbsent(Key.Hello, s -> {
    map.computeIfAbsent(Key.Hello, t -> 1);
    return 2;
});

enum Key {Hello}
While this might seem like a strange thing to do in simple cases, in more complex code you could do this by accident (as I did this afternoon)  So what happens?  Well it depends on the collection you are using.
HashMap: {Hello=2}
WeakHashMap: {Hello=2}
TreeMap: {Hello=2}
IdentityHashMap: {Hello=2}
EnumMap: {Hello=2}
Hashtable: {Hello=2, Hello=1}
LinkedHashMap: {Hello=1, Hello=2}
ConcurrentSkipListMap: {Hello=1}
ConcurrentHashMap: 
Note: ConcurrentHashMap never returns.  It's locking doesn't appear to be re-entrant.
ConcurrentSkipListMap has the most reasonable result, retaining the first value added.  Hello=2 is reasonable for this undefined situation, if confusing as it is the second value not the first.  What doesn't make much sense is to have the unique immutable key appear twice.
Having ConcurrentHashMap deadlock itself is unfortunate but at least its not subtle.
The complete code.
public class A {
    public static void main(String[] args) {
        for (Map map : new Map[]{
                new HashMap<>(),
                new WeakHashMap<>(),
                new TreeMap<>(),
                new IdentityHashMap<>(),
                new EnumMap<>(Key.class),
                new Hashtable<>(),
                new LinkedHashMap<>(),
                new ConcurrentSkipListMap<>(),
                new ConcurrentHashMap<>()
        }) {
            System.out.print(map.getClass().getSimpleName() + ": ");
            map.computeIfAbsent(Key.Hello, s -> {
                map.computeIfAbsent(Key.Hello, t -> 1);
                return 2;
            });
            System.out.println(map);
        }
    }

    enum Key {Hello}
}

The method compute() has similar results
HashMap: {Hello=null2}
WeakHashMap: {Hello=null2}
TreeMap: {Hello=null2}
IdentityHashMap: {Hello=null2}
EnumMap: {Hello=null2}
Hashtable: {Hello=null2, Hello=1}
LinkedHashMap: {Hello=1, Hello=null2}
ConcurrentSkipListMap: {Hello=12}
ConcurrentHashMap:
Conclusion
You need to be careful if you nest calls to a map from inside a lambda, or avoid doing so at all.  If you have to do this, ConcurrentSkipListMap appears to behave the best.

The Java Zone is brought to you in partnership with ZeroTurnaround. Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code!

Topics:

Published at DZone with permission of Peter Lawrey, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}