跪拜 Guibai
← All articles
Android

Five Concurrency Traps in a Tiny Kotlin Coroutine Code Review

By 潜龙勿用之化骨龙 ·
Read original on juejin.cn ↗ Google Translate ↗ Alt translation

The pitfalls shown here appear often in real Android and Kotlin codebases: misused Java locks creep into coroutines, and Dispatchers leak into use cases that should stay agnostic. Fixing them simplifies concurrency and makes components honest about Main-safety.

Summary

The article presents a short `DocumentImportUseCase` that imports files concurrently, and challenges readers to review it. The first problem is locking on the UseCase instance with `synchronized(this)`; it protects the wrong object and can cause unrelated critical sections to contend. Moving the lock to a dedicated object fixes the immediate contention but misses a deeper issue: why share a `MutableList` at all when each coroutine can return its own result.

The proposed solution uses `async` to let each file parse and insert independently, then `awaitAll().filterNotNull()` to collect only new documents. This removes the need for locks and shared mutable state entirely. The fourth issue is injecting `ioDispatcher` into the UseCase; the article argues that Parser and Repository should expose Main-safe suspending APIs and handle their own thread switching, so the UseCase only orchestrates business logic. The final implementation drops the Dispatcher, resulting in cleaner, more testable code.

The article closes with a question about whether `ConcurrentHashMap` can be replaced with `HashMap` inside the Repository, inviting readers to reason about atomicity and visibility in suspending APIs.

Takeaways
— Locking on the UseCase instance (or any shared business object) with `synchronized` is risky; a dedicated lock object or locking the collection itself is safer.
— Even with a correctly placed lock, sharing a `MutableList` among coroutines is unnecessary if each task can return a value.
— Using `async` and `awaitAll().filterNotNull()` eliminates the need for locks and shared mutable state in this import scenario.
— Data that can be passed via return values should not be passed via shared mutable state; this reduces contention and complexity in concurrent code.
— UseCase should not take a `CoroutineDispatcher` unless it genuinely owns the threading; Parser and Repository should provide Main-safe suspending APIs with their own internal scheduling.
— Main-safe does not mean a suspend function automatically switches off the main thread; the component must actually implement `withContext` or equivalent.
— The final design has Parser handle parsing, Repository handle atomic insertion, and UseCase orchestrate the flow.
— `ConcurrentHashMap.putIfAbsent` gives atomicity for the same ID; swapping to a plain `HashMap` without synchronization would break that guarantee.
Conclusions

The article illustrates that Java's `synchronized` mindset translates poorly to coroutines; when every task can return a value, the need for locking disappears.

The Refactoring from `launch` + shared list to `async`+`awaitAll` is a clean example of how structured concurrency encourages deterministic results over side effects.

Injecting a Dispatcher into a UseCase often signals that lower layers are not honoring their Main-safe contracts, pushing thread decisions into business logic.

The closing question about `ConcurrentHashMap` vs `HashMap` points to a common gap: developers know the collection exists but may not reason about what happens inside a suspending function that runs on multiple threads.

Concepts & terms
Main-safe API
A suspending function that can be safely called from the main thread because it internally switches to the appropriate dispatcher for blocking work, so callers don't need to manage threading.
Structured concurrency
A coroutine scope that guarantees child coroutines complete before the parent returns, used here with `coroutineScope` and `async` to collect results in a deterministic way.
Dedicated lock object
A private `Any()` instance used only as a mutex for a specific shared resource, instead of locking on an externally visible business object.
Source: juejin.cn ↗ Google Translate ↗ Backup ↗