liveBook · Manning

runBlocking

As explained in Kotlin in Action, 2E

runBlocking is a kotlinx.coroutines coroutine builder that blocks the current thread while executing a coroutine and its suspending operations.

runBlocking bridges ordinary blocking code and suspending functions. It creates and runs a coroutine, blocks the current thread until completion, and lets its body call suspending functions. section 14.6 section 14.6.1

Listing 14.6 Using runBlocking to invoke a suspending function
import kotlinx.coroutines.*
import kotlin.time.Duration.Companion.milliseconds
 
suspend fun doSomethingSlowly() {
    delay(500.milliseconds)          #1
    println("I'm done")
}
 
fun main() = runBlocking {
    doSomethingSlowly()
}

A compact Kotlin program uses runBlocking to call doSomethingSlowly, which suspends with delay before printing. section 14.6.1

Inside the block, delay suspends the coroutine rather than blocking additional threads. This makes runBlocking useful as an entry point into coroutine code, while launch can start child coroutines within it. section 14.6.1

Structured concurrency gives runBlocking a defined completion boundary:

  • The block establishes a coroutine scope, so launch and async coroutines created inside it become children. section 15.1
  • runBlocking waits for its child coroutines and their descendants before returning, even when its own body finishes earlier. section 15.1

How Kotlin in Action, 2E covers it

How deep it goes
Explains current-thread blocking, suspension, child coroutines, and structured waiting without detailing implementation internals.
Examples
Uses a main function, doSomethingSlowly, delay, println, and child launch operations to demonstrate completion behavior.
What it assumes
Introduces coroutines and coroutine builders while assuming only a need to call suspending functions from regular code.
What you can do after
Apply it via kotlinx.coroutines to invoke suspending functions and wait for structured child-coroutine completion.
How it connects
Connects runBlocking with coroutines, suspending functions, coroutine scopes, launch, async, and structured concurrency.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.