Five Concurrency Traps in a Tiny Kotlin Coroutine Code Review
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.
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.
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.