Fix the compute call counter for a cache
Your task
A Java cache checks containsKey, then calls compute(key) and put. An AI said it computes each key at most once, but under concurrency several threads can all see the key missing and all compute it. You are about to put an expensive remote call inside compute, so you model how many calls each design makes.
An assistant wrote count_compute_calls(request_waves, atomic). It is in the editor. It has a bug. Find it and fix it.
Input and output:
request_waves: groups of concurrent requests, each a list of keys. Within a wave, every request checks the cache before any of that wave's results are stored.atomic:falsemodels check-then-put,truemodelscomputeIfAbsent.- Return the total number of
computecalls.
Rules the tests check:
- The cache starts empty. After each wave, every key the wave asked for is in the cache.
- A request for a key already in the cache is a hit and never calls
compute, in either design. - With
atomicfalse, every other request in a wave callscompute, even several for the same key. - With
atomictrue, each missing key is computed once per wave, however many requests ask for it.
Examples
count_compute_calls(request_waves: list[list[str]], atomic: bool) -> intExample 1
Input
count_compute_calls([["k", "k", "k", "k", "k", "k", "k", "k"]], False)Output
8Example 2
Input
count_compute_calls([["k", "k", "k", "k", "k", "k", "k", "k"]], True)Output
1