Kotlin · Coroutines
Kotlin suspend functions interview question
The suspend keyword lets a Kotlin function pause and resume inside a coroutine. Explain separately which thread runs the work and whether the work itself blocks.
Published by RoleHello. References are linked in the guide.
Does suspend move work to a background thread?
No. Marking a function suspend allows it to call other suspending functions and suspend its execution. It does not launch a coroutine or select a background thread. The caller’s coroutine context determines where the function runs unless the code changes that context.
A suspending operation such as delay can pause the coroutine while releasing the thread for other work. A blocking call such as Thread.sleep still occupies its thread, even inside a suspending function. Adding suspend to a function that calls a blocking API does not make that API nonblocking.
For blocking file I/O on the JVM, use a dispatcher intended for that work:
import java.nio.file.Files
import java.nio.file.Path
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
suspend fun readSettings(path: Path): String =
withContext(Dispatchers.IO) {
Files.readString(path)
}
withContext runs the block in the requested context and suspends the caller while it waits for completion. Files.readString still blocks an I/O worker thread. The benefit is keeping that blocking operation off a caller such as the Android main thread. Dispatchers.IO may share threads with other dispatchers, so changing context does not always mean switching to a different physical thread.
Use Dispatchers.Default for substantial CPU work. If a library already provides a nonblocking suspending API, follow its threading contract rather than wrapping every call in Dispatchers.IO.
Cancellation is also separate from the suspend modifier. A blocking operation does not automatically stop when its coroutine is cancelled. Check the API’s cancellation behavior and release resources when work finishes or fails.
In an interview, describe the operation, the caller’s context, and the reason for choosing a dispatcher. That explains the behavior more clearly than calling every suspending function a background task.