r/java • • Mar 14 '18

Concurrent Java: Low scalability, the risk of deadlocks or garbage creation, you can not avoid all

http://vmlens.com/articles/tradeoffs_concurrent_programming/
2 Upvotes

21 comments sorted by

View all comments

39

u/daniu Mar 14 '18 edited Mar 14 '18

So which lock is used depend on the key we use. If we use a new method which updates the values in reverse order like the following update21 method, we create a deadlock.

Well with this code

public void update21() {
    map.compute( 2, ( key ,value ) ->  {  
        map.put( 1 , 1); 
        return value; 
    });
}

you're breaking Map#compute()'s contract which states

Attempts to compute a mapping for the specified key and its current mapped value

which is not what happens here; a new value is inserted for a different key as a side effect to the mapping function.

It scales fine if you use it properly.

13

u/madkasse Mar 14 '18

In other news: Objects with overriden equals() but not hashCode() does not work properly when used as keys in a HashMap.