跪拜 Guibai
← Back to the summary

Five Concurrency Traps in a Tiny Kotlin Coroutine Code Review

A Kotlin Coroutine Code Snippet Hides 5 Problems: Can You Spot Them?

Let's look at a piece of Kotlin coroutine code.

This is a file import scenario: multiple coroutines parse files concurrently, and only new documents are added to the result list.

class DocumentImportUseCase(
    private val repository: DocumentRepository,
    private val parser: DocumentParser,
    private val ioDispatcher: CoroutineDispatcher
) {
    suspend fun importAll(files: List<File>): List<Document> {
        val added = mutableListOf<Document>()
        coroutineScope {
            files.forEach { file ->
                launch(ioDispatcher) {
                    val document = parser.parse(file)
                    val isNew = repository.insertIfAbsent(document)
                    if (isNew) {
                        synchronized(this@DocumentImportUseCase) {
                            added.add(document)
                        }
                    }
                }
            }
        }

        return added
    }
}

If you were asked to do a Code Review, what issues would you raise?

Don't rush to look below, take a minute to find them yourself.

This is a separator













This code has at least five points worth discussing, involving Java concurrency, Kotlin coroutines, Main-safety, and responsibility division in modern Android architecture.

I've always felt that code review best reflects an engineer's technical depth.

If you can spot the unreasonable position of the synchronized(this) lock, your Java concurrency basics are solid.

If you can further discover that this code doesn't actually need a lock, you have a deeper understanding of Kotlin coroutines.

If you can also spot the concurrency safety issue in the Repository and the boundaries of Dispatcher usage, you are already reviewing code from a whole-system perspective.

Let's analyze each point below.

Problem One: Why is synchronized(this) not a good choice?

First look at this code:

synchronized(this@DocumentImportUseCase) {
    added.add(document)
}

Here the UseCase instance is used as the lock object.

From a Java concurrency perspective, what is wrong with this approach?

synchronized locks the monitor of the object.

Only threads competing for the same monitor will be mutually exclusive.

The issue is that what actually needs protection is added, not the whole UseCase instance.

The UseCase instance may be used by other code, and could also appear elsewhere:

synchronized(this) {
    // other operations
}

Two unrelated critical sections might then contend unnecessarily because they share the same lock object.

More importantly, the UseCase instance may be exposed to external code, which can also use it as a lock object.

The choice of lock should express the shared state being protected as precisely as possible.

For example:

synchronized(added) {
    added.add(document)
}

Or:

private val lock = Any()

// inside concurrent task
synchronized(lock) {
    added.add(document)
}

A dedicated lock object is usually clearer and avoids making a business object part of the synchronization protocol.

At this point, at least we can say we've found the first problem.

But this is not the best answer yet.

Problem Two: Once the lock is moved, is the design correct?

We've now moved the lock from the UseCase instance to a dedicated lock object.

Is the problem solved?

Not really.

We've only made concurrent writes to the shared list safe.

But there's a question worth further thought:

Why must multiple coroutines mutate one list together?

Look at the original business logic:

val document = parser.parse(file)
val isNew = repository.insertIfAbsent(document)

if (isNew) {
    synchronized(lock) {
        added.add(document)
    }
}

Each coroutine does something simple:

  1. Parse one file.
  2. Save the document.
  3. Check if it's new.
  4. If new, return the document.

Each coroutine can independently produce its own result.

So why must all coroutines share a MutableList?

This brings us to another approach.

Problem Three: Don't share state, let coroutines directly return results

In Kotlin coroutines, async and await solve this nicely.

suspend fun importAll(files: List<File>): List<Document> =
    coroutineScope {
        files.map { file ->
            async(ioDispatcher) {
                val document = parser.parse(file)
                val isNew = repository.insertIfAbsent(document)
                if (isNew) document else null
            }
        }.awaitAll().filterNotNull()
    }

What happens here?

Each async handles one file.

The parent coroutine collects all child coroutine results via awaitAll(), then filters out nulls with filterNotNull().

Now there's no need for:

The data flow becomes:

        File list
          |
     coroutineScope
          |
    +-----+-----+
    |     |     |
  async async async
    |     |     |
  result1 result2 result3
    |     |     |
    +-----+-----+
          |
       awaitAll
          |
     filterNotNull
          |
     final result

There is a very important concurrency principle here:

Data that can be passed through return values should not be passed through shared mutable state.

This is not only a Kotlin coroutine technique, but also an important idea in concurrent programming to reduce contention and lower complexity.

Problem Four: Why should UseCase know about the IO Dispatcher?

The last problem is also worth discussing in modern Android architecture.

The original UseCase:

class DocumentImportUseCase(
    private val repository: DocumentRepository,
    private val parser: DocumentParser,
    private val ioDispatcher: CoroutineDispatcher
)

Why inject ioDispatcher?

If the only reason is that file reading and database operations need IO, is that responsibility misplaced?

Let's look at the two interfaces:

interface DocumentParser {
    suspend fun parse(file: File): Document
}

interface DocumentRepository {
    suspend fun insertIfAbsent(document: Document): Boolean
}

They should provide Main-safe APIs to the caller.

That is:

For example:

class DefaultDocumentParser(
    private val ioDispatcher: CoroutineDispatcher
) : DocumentParser {

    override suspend fun parse(file: File): Document =
        withContext(ioDispatcher) {
            // file reading and parsing
        }
}

Repository can also handle its own blocking operations internally.

Then UseCase doesn't need to know whether the underlying layer uses IO, Default, or some other execution context.

The key point is:

Don't make the caller responsible for thread safety and blocking handling that should be handled by lower-level components.

Also, don't forget: Main-safe does not mean automatically switching threads. A suspend function can perfectly execute blocking operations on the main thread. Components must truly implement their own Main-safe contract.

Final Implementation: Can it be even simpler?

After the above analysis, we can simplify the UseCase like this:

class DocumentImportUseCase(
    private val repository: DocumentRepository,
    private val parser: DocumentParser
) {
    suspend fun importAll(files: List<File>): List<Document> =
        coroutineScope {
            files.map { file ->
                async {
                    val document = parser.parse(file)
                    val isNew = repository.insertIfAbsent(document)

                    if (isNew) document else null
                }
            }.awaitAll().filterNotNull()
        }
}

Now the implementation:

Each component handles its own responsibility:

Parser is responsible for parsing, Repository for atomic saving, UseCase for business orchestration.

This is the design we really hope to see.

A question left for you: Can ConcurrentHashMap be replaced with HashMap?

At the end, leave a slightly interesting question.

Assume the Repository internally uses the following data structure:

private val documents = ConcurrentHashMap<String, Document>()

The insertion logic:

override suspend fun insertIfAbsent(
    document: Document
): Boolean {
    return documents.putIfAbsent(
        document.id,
        document
    ) == null
}

Here ConcurrentHashMap is used to guarantee atomic insertion for the same ID via putIfAbsent.

Now the question:

If we replace ConcurrentHashMap with a plain HashMap, what impact would there be?

private val documents = HashMap<String, Document>()

Don't rush to answer.

Leave this question to everyone, and put your answers in the comments.

Source code: https://github.com/ThirdPrince/KotlinCoroutines_Delay/tree/main/src/main/kotlin/document_import

Comments

Top 2 of 5 from juejin.cn, machine-translated. The original thread is authoritative.

Android打工仔

Good article, worth reading repeatedly.

潜龙勿用之化骨龙

Spotted a few issues.

Android打工仔  → 潜龙勿用之化骨龙

Four, I didn't notice the issue of using usecase as a lock.

冬天里的Java

Damn, I didn't spot even one.