ConcurrentHashMap ComputeIfAbsent Failure Path

Keep ConcurrentHashMap clean when computeIfAbsent returns null or throws: failed loads leave the key absent so a subsequent retry can succeed.

JavaResilience

Code

snippet
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

public class SafeCacheLoad {

    public static void main(String[] args) {
        ConcurrentHashMap<String, String> tokens = new ConcurrentHashMap<>();
        AtomicInteger attempts = new AtomicInteger();

        // Returning null leaves the key absent (no null entries cached)
        String missing = tokens.computeIfAbsent("guest", k -> null);
        System.out.println("null mapping -> result=" + missing + " size=" + tokens.size());

        // Throwing inside the mapping function aborts insertion cleanly
        try {
            tokens.computeIfAbsent("svc-a", k -> {
                attempts.incrementAndGet();
                throw new IllegalStateException("upstream down");
            });
        } catch (IllegalStateException ex) {
            System.out.println("first load failed: " + ex.getMessage());
        }
        System.out.println("key present after exception: " + tokens.containsKey("svc-a"));

        // Subsequent call retries and populates the key once
        String loaded = tokens.computeIfAbsent("svc-a", k -> {
            attempts.incrementAndGet();
            return "token-v" + attempts.get();
        });
        String cached = tokens.computeIfAbsent("svc-a", k -> "unused");
        System.out.println("loaded=" + loaded + " cached=" + cached + " attempts=" + attempts.get());
    }
}

Implementation flow — ConcurrentHashMap ComputeIfAbsent Failure Path

All of the logic lives in the class SafeCacheLoad and the function main.

IllegalStateException is thrown inside a try block — the matching handler clause, not any input check, decides what happens to it.

What to watch for

  • Zero dependencies by design — no external registry lookups or lockfile entries.

Using it

The entry-point signature is public static void main(String[] args)

Output lines are prefixed (null mapping -> result=, first load failed:, key present after exception:), mapping every printed status line back onto a code transition.

Key statements

throw new IllegalStateException("upstream down");
return "token-v" + attempts.get();

Interactive Tools for This Topic

FAQ

Does the snippet validate its input?
No — the `IllegalStateException` is raised inside a `try` block: execution reaches it unconditionally, and the surrounding handler clause decides what catches it. There is no input check in the snippet.
What does ConcurrentHashMap ComputeIfAbsent Failure Path print when run?
The script runs standalone; its 4 labeled outputs include `null mapping -> result=`, `first load failed:`, `key present after exception:`.