Kotlin
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
170: Coroutine Performance Best Practices
When people first get comfortable with coroutines, the general vibe is "they're lightweight, so just launch a thousand of them!" While it's true that coroutines aren't threads, they aren't free. If you're not careful about how you handle dispatchers and context switching, you can actually make your app slower than if you'd just used a simple Thread.
To show you what I mean, let's build a LogAnalyzer. The goal is simple: read a massive list of log files from a disk, parse the contents for specific error patterns (which is CPU-intensive), and save the results to a database. It's a classic "I/O then CPU then I/O" sandwich.
The temptation of "just launch everything"
My first instinct—and probably yours too—is to just wrap everything in a launch block using Dispatchers.IO because, well, we're reading files. Here is how I started the implementation:
suspend fun analyzeLogs(files: List<File>) = coroutineScope {
files.forEach { file ->
launch(Dispatchers.IO) {
val content = file.readText() // I/O
val results = parseLogs(content) // CPU Intensive
saveToDb(results) // I/O
}
}
}
At first glance, this looks efficient. It's concurrent! But here is where I hit a wall. When I ran this against 10,000 small files, the memory usage spiked, and the CPU was thrashing. Why? Because I'm performing heavy parsing—parseLogs(content)—on Dispatchers.IO.
Correcting the Dispatcher mismatch
I made a rookie mistake here. Dispatchers.IO is designed to offload blocking calls; it creates a large pool of threads because it expects those threads to be sitting around waiting for a disk or network response. However, parseLogs is purely computational. By running CPU-heavy work on the IO dispatcher, I'm forcing the system to manage way more active threads than there are physical CPU cores, leading to excessive context switching.
The fix is to isolate the CPU work. I need to move the parsing logic to Dispatchers.Default, which is sized exactly to the number of available cores. I'll use withContext to switch just for that specific part of the pipeline:
suspend fun analyzeLogs(files: List<File>) = coroutineScope {
files.forEach { file ->
launch(Dispatchers.IO) {
val content = file.readText()
// Switching to Default for the heavy lifting
val results = withContext(Dispatchers.Default) {
parseLogs(content)
}
saveToDb(results)
}
}
}
This is better, but we're still launching 10,000 coroutines. Even if they are lightweight, we're flooding the saveToDb function, which likely hits a database connection pool that can only handle, say, 10 concurrent connections. We're basically DDoS-ing our own database.
Taming throughput with limited parallelism
To stop the database from choking, I don't want to use a Semaphore or a complex queue if I can avoid it. Instead, I'll use limitedParallelism. This is a relatively recent addition to the Kotlin Coroutines API that allows us to create a "view" of a dispatcher that limits how many coroutines can run concurrently.
I'll create a dedicated dispatcher for the database writes to ensure we never exceed the connection limit, while still letting the file reading happen as fast as the OS allows.
val dbDispatcher = Dispatchers.IO.limitedParallelism(10)
suspend fun analyzeLogs(files: List<File>) = coroutineScope {
files.forEach { file ->
launch(Dispatchers.IO) {
val content = file.readText()
val results = withContext(Dispatchers.Default) {
parseLogs(content)
}
// Now we limit the concurrency of the DB writes
withContext(dbDispatcher) {
saveToDb(results)
}
}
}
}
Now the flow is optimized: the OS handles the file reads via the broad IO pool, the CPU handles the parsing via the core-limited Default pool, and the database is protected by a strict limit of 10 concurrent writes. This prevents the "thundering herd" problem and keeps the memory footprint stable.
📋 Practical Task
Exercise: Optimizing a High-Frequency Image Filter Pipeline
You are building a photo editing app. You have a list of 500 high-resolution images that need to be processed. The pipeline works like this: 1. Load the image from disk (I/O). 2. Apply a complex Gaussian Blur filter (CPU heavy). 3. Save the processed image back to disk (I/O).
Currently, the code looks like this:
suspend fun processImages(images: List<File>) = coroutineScope {
images.forEach { image ->
launch(Dispatchers.IO) {
val bitmap = loadImage(image)
val blurred = applyBlur(bitmap)
saveImage(blurred)
}
}
}
Your Task: Rewrite the processImages function to implement the performance best practices learned in this lesson. Specifically:
- Ensure the
applyBlurfunction runs on the appropriate dispatcher for CPU-bound work. - Prevent the app from overloading the disk I/O during the
saveImagephase by limiting the concurrency of saves to a maximum of 4 simultaneous operations.
There are no comments for now.