Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance of ConcurrentHashMap.putIfAbsent

In his talk about Effective Java at 54:15 Joshua Bloch recommends to use get before putIfAbsent in order to improve performance and concurrency. This leads me to the question why this optimization is already not build in like

public V BETTER_putIfAbsent(K key, V value) {
    V result = get(key);
    if (result!=null) return result;
    return ORIGINAL_putIfAbsent(key, value);
}
like image 746
maaartinus Avatar asked Oct 11 '22 06:10

maaartinus


1 Answers

I would guess that it is because performance depends on the usage pattern. For a map where most putIfAbsent calls would succeed, then guarding it with a get will be slower. For a map where putIfAbsent will often fail, then guarding it with a get will be faster.

By not making the optimization for the common failure case, you are free to choose which method is faster for your map.

In the example from the video, putIfAbsent will usually fail, so it is faster to guard it with a get.

like image 123
sbridges Avatar answered Oct 14 '22 04:10

sbridges