Fix the compute call counter for a cache

Review the AI's codeEasy10 min

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: false models check-then-put, true models computeIfAbsent.
  • Return the total number of compute calls.

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 atomic false, every other request in a wave calls compute, even several for the same key.
  • With atomic true, 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) -> int
Example 1
Inputcount_compute_calls([["k", "k", "k", "k", "k", "k", "k", "k"]], False)
Output8
Example 2
Inputcount_compute_calls([["k", "k", "k", "k", "k", "k", "k", "k"]], True)
Output1