1. What “I/O blocks a thread” means
If you used to perceive “blocking” as something like “the program froze,” today we will break it down into a simple, almost everyday mechanism. It is important to understand one thing: a coroutine is not a thread, and a thread is not a coroutine. A coroutine is an “execution scenario” that can be suspended, while a thread is a real working “executor” that at a specific moment does one specific job.
A blocking operation is an operation that makes a thread wait until the outside world finishes an action. For example, reading a file may have to wait for the disk, the file system, the OS cache, access permissions, antivirus (yes, it sometimes “helps” too), and a bunch of other things. While the thread is waiting, it cannot run other coroutines. It is like hiring a courier (a thread) and having them stand in line at the post office (blocking I/O) — technically they are “at work,” but they are not doing useful work right now.
Coroutine “magic” begins where an operation can suspend without holding onto the thread. For example, delay(...) suspends the coroutine, but the thread is released and can run other tasks. This is one of the key reasons coroutines are considered lightweight and convenient for concurrency.
To avoid mixing up the intuition, keep a simple formula in mind:
- Suspension (for example delay) → the coroutine waits, the thread is free.
- Blocking (for example reading a file via the regular File API) → the thread waits, and the coroutines on that thread also “wait together with it.”
2. Why file operations are most often blocking
It is very tempting to believe that “a file on disk is almost like a variable in memory, just bigger.” But in practice, a file is a contract with the operating system. Even if you call something as simple as exists() or length(), under the hood it may mean a request to a file system that can be local, networked, cached, slow, suddenly unavailable — and all of that happens outside your program.
When you call File("data.txt").readText(), your thread at some point makes a system call and may actually wait. Sometimes the wait is small, sometimes large, sometimes “why did this take 2 seconds, the file is on an SSD?” The answer is usually: “because you do not control the outside world.”
Here it is important not to bury ourselves in OS details, but to take a practical idea: the usual file API on the JVM is blocking by nature. This is not “bad” or “outdated,” it is simply a different class of operations. Coroutines do not automatically change the nature of this operation: they only give you tools to carefully choose where (on which threads) you will do it.
And this is where the question of the day appears: if file operations block a thread, then which thread are we willing to block?
3. Dispatchers.Default and Dispatchers.IO: a simple model
The word Dispatcher sounds like “thread schedules,” “time-slice allocation,” and mild panic are about to appear. But we do not need to know the internals of the scheduler to write good code. We need an understandable everyday model: a Dispatcher chooses which thread pool a coroutine will run on.
In the Kotlin documentation, coroutines are described as a convenient way to do concurrency, and CoroutineDispatcher is mentioned as part of the context that determines where the coroutine executes. That is exactly what we need right now.
Here is a simple table (and yes, you can print it out and hang it next to your monitor — next to “do not commit to master”):
| Dispatcher | What it is mentally intended for | What would be a bad idea |
|---|---|---|
|
CPU work: computations, parsing, collection processing, sorting, “calculate something heavy” | Blocking a thread for a long time on files/network/waits |
|
Blocking I/O: files, input/output streams, disk access | Shoving heavy computations in there “just in case” |
The point is the following. Default is usually sized around the number of CPU cores: it is a limited resource. If you occupy its threads with waiting for disk, then other CPU tasks will wait, even though the CPU could have been working.
And IO is the place where it is conceptually “allowed” to block threads on input/output waits, so that you do not ruin life for compute-heavy tasks.
4. Demonstrating the problem: blocking Default slows down CPU
Now for a small “on your fingers” example. We will not build a world-class benchmark (we will leave that to people who argue about 0.3% performance in comments), but we will see the effect: if you run blocking work on Dispatchers.Default, you can worsen the execution of other tasks on Default.
Let us imagine we have a console app called BudgetBuddy (our hypothetical practical project) that can compute spending statistics. At some point it reads a data file and then computes the total. Reading the file is I/O; computing is CPU.
We will make two functions: one “does” CPU work, the other simulates blocking disk access (via Thread.sleep, because that is the most honest way to show “the thread is busy and waiting,” and in terms of feel it is close to reading a large file).
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
suspend fun cpuWork(): Long = withContext(Dispatchers.Default) {
var sum = 0L
for (i in 1..5_000_000) sum += i
sum
}
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
suspend fun fakeFileReadBlocking(): String = withContext(Dispatchers.Default) {
Thread.sleep(300) // simulate waiting for disk (the thread is really busy!)
"file-read-done"
}
Notice: in the second function we intentionally do it badly — we block Default. This is a teaching “setup” to see the consequences.
Now let us run both tasks in parallel:
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import kotlin.system.measureTimeMillis
fun main() = runBlocking {
val timeMs = measureTimeMillis {
val cpu = async { cpuWork() }
val io = async { fakeFileReadBlocking() }
println("cpu=${cpu.await()}") // cpu=12500002500000
println("io=${io.await()}") // io=file-read-done
}
println("total=${timeMs}ms") // total=...
}
In this example, it may happen that the CPU work finishes noticeably later than it could have, because some Default threads were occupied with “file waiting.” With small numbers and fast machines this is not always dramatic, but the principle matters more than the digits.
Now the key idea: if “file waiting” takes up Default threads, then those threads are unavailable for CPU work. Which means you created a checkout line for yourself even though you could have opened another register.
5. Practice: I/O on Dispatchers.IO, CPU on Default
Rule: send file operations to Dispatchers.IO
Now we will fix the mistake from the previous section. The fix is surprisingly simple, and that is exactly why it is so easy to ignore (the brain likes: “come on, it works anyway”). We simply acknowledge reality: “this is I/O,” and run the blocking part on Dispatchers.IO.
Let us rewrite the “file read” so it runs on IO:
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
suspend fun fakeFileReadRight(): String = withContext(Dispatchers.IO) {
Thread.sleep(300) // still blocking, but now on the IO pool
"file-read-done"
}
And again we run in parallel:
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import kotlin.system.measureTimeMillis
fun main() = runBlocking {
val timeMs = measureTimeMillis {
val cpu = async { cpuWork() }
val io = async { fakeFileReadRight() }
println("cpu=${cpu.await()}") // cpu=12500002500000
println("io=${io.await()}") // io=file-read-done
}
println("total=${timeMs}ms") // total=...
}
Now “file waiting” does not occupy compute threads. The CPU task can breathe more freely, and the overall behavior of the program becomes more predictable: computations run where they belong, and I/O runs where we are not afraid of blocking.
Important: we did not make I/O non-blocking. We made it architecturally tidy: the blocking happens in the right place.
Mini-architecture: “I/O separately, CPU separately”
At this point, many people want to ask an honest question: “OK, I get that I need Dispatchers.IO. But why not just shove everything into IO and not think?” You can. It will work. Sometimes. And then you will be surprised why the app loads the system “weirdly” and why you cannot explain where your CPU bottleneck is and where your I/O bottleneck is.
It is better to keep a simple discipline: where we interact with the outside world, use an I/O context; where we purely compute, use Default (or the current context if it is compute-oriented). This discipline is not about “optimization for optimization’s sake,” but about making the code read like an honest story: “here I read a file,” “here I compute.”
This is especially noticeable in applications like our BudgetBuddy. Imagine we have a scenario: “read a CSV of expenses and compute the sum.” Bad style is to mix everything in one place and also on the wrong dispatcher. Good style is to at least mentally separate the stages.
Here is a minimal sketch (without diving into CSV reading details; the idea is what matters now):
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
suspend fun loadExpensesText(path: String): String = withContext(Dispatchers.IO) {
File(path).readText()
}
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
suspend fun totalFromText(text: String): Long = withContext(Dispatchers.Default) {
// suppose each line is a number
text.lineSequence()
.filter { it.isNotBlank() }
.sumOf { it.trim().toLong() }
}
Yes, that is two functions instead of one. But now it is visible where I/O is and where CPU is. And if tomorrow it turns out parsing became heavy, you will not accidentally do it on IO “because that is how it historically happened.”
To cement it in your head, here is a simple diagram (there is no secret magic in it, just honest separation of responsibilities):
flowchart TD
A["Need to compute the total expenses"] --> B["Read the file"]
B -->|blocking File API| C["Dispatchers.IO"]
C --> D["Got the text"]
D --> E["Parse and compute"]
E --> F["Dispatchers.Default"]
F --> G["Result: total"]
6. Typical mistakes
Mistake #1: “I am in a coroutine, so I am not blocking.”
This is one of the most common traps. A coroutine is not a guarantee of non-blocking behavior; it is a convenient way to manage concurrency. If inside a coroutine you call a blocking function (for example, reading a file via the regular File API), then the thread will wait. A good habit here is to always ask yourself: “Is this operation waiting for the outside world, or is it only computing?”
Mistake #2: file operations run on Dispatchers.Default “because it is easier.”
Most often it looks harmless: “I just read a file once.” The problem appears when those “once” become many, or when the file is large, or when the disk is suddenly slow. Default is valuable space for computations. If you block it with I/O, coroutines that truly need to compute will start to suffer.
Mistake #3: trying to fix everything by sending everything to Dispatchers.IO.
This is the opposite extreme. Yes, the app may stop “hanging” on computations, but you lose structure: now it is unclear where the CPU load is and where the I/O is. Plus you can get strange performance effects: computations and I/O will compete inside one pool “for no reason.” The discipline “I/O separately, CPU separately” is first and foremost about code clarity.
Mistake #4: underestimating “small” file calls (exists(), length(), isFile).
Sometimes it seems: “well, it is just a check.” But it is still a call to the file system, which is a potentially blocking operation. In a real project, it is useful to adhere to a single style: treat any touch of the file system as I/O and perform it in an appropriate context. Then there will be no surprises when a “harmless check” suddenly starts slowing down in an unexpected place.
GO TO FULL VERSION