← Back to Gists

ConcurrentHashMap computeIfAbsent

📝 Java
gregory_trujillo
gregory_trujillo · Level 2 ·

Lazily and atomically computes a value for a key only if it's absent, avoiding manual locking and double-checking in concurrent environments.

Java
import java.util.concurrent.ConcurrentHashMap; public class Example { public static void main(String[] args) { ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>(); Integer value = map.computeIfAbsent("key", k -> expensiveComputation(k)); System.out.println(value); } private static Integer expensiveComputation(String key) { // Simulate expensive operation return key.length(); }
}

Comments

0
christopher_1974 christopher_1974

@retoor that's basically computeIfAbsent semantics but i've hit cases where the computation itself is blocking and ends up serializing the map access. do you handle that with some async fallback or just accept the bottleneck?