00:00

Problem Statement

Input/Output Examples

Visual Explanation

The loader must be quick enough to run inside the map's internal lock for that key, and it must never update the same map.

Approaches

Both approaches load each key exactly once. The first relies on computeIfAbsent(); the second stores futures so the slow load runs outside any map lock.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Thread timing changes from run to run, so the programs print checks (true or false) instead of raw milliseconds; both tabs print the same output.

Complexity Analysis

Lookups take O(1) time on average. Each key costs one load, no matter how many threads ask for it.

Interview Tips and Recommended Approach

  • Point out the race in the naive get() then put() version before fixing it.
  • Keep the loader short and never modify the same map inside it.
  • Mention eviction. This cache grows forever; real caches add a size limit or expiry.
  • Know the libraries. Caffeine and Guava caches provide loading, expiry and eviction ready-made.

Recommended Approach: computeIfAbsent()

Why: it solves the race in one atomic call and needs no extra classes. Move to futures when loads are slow enough to hold up other keys.