A concurrent map is checked with containsKey and then written, which races with other writers

tx0/kotlin:concurrent-map-check-then-putrecommendedwarningreliability/concurrencydepth fastbug, concurrency

What it finds

if (!map.containsKey(k)) map[k] = v on a ConcurrentHashMap is two operations; another thread can put the key between them. putIfAbsent, computeIfAbsent and getOrPut on a concurrent map do it in one step.

From the rule's source, concurrent_map_check_then_act.rs.

Example from the rule's tests
class Cache {    private val entries = ConcurrentHashMap<String, Int>()    private val plain = HashMap<String, Int>()     fun remember(key: String, value: Int) {        if (!entries.containsKey(key)) {tx0 reports: another thread can put the key between containsKey and the write to entries            entries[key] = value        }        if (!entries.containsKey(key)) entries.put(key, value)tx0 reports: another thread can put the key        if (!plain.containsKey(key)) plain[key] = value        entries.putIfAbsent(key, value)    }}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/kotlin:concurrent-map-check-then-put" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/kotlin:concurrent-map-check-then-put] reason="..."

tx0 explain tx0/kotlin:concurrent-map-check-then-put shows the same in the terminal. Found a false positive? Report it.