kotlinconcurrencykotlin-coroutines

Can the coroutine launched through runBlocking be executed on 2 or more threads?


I have this runBlocking code and I wanted to know if its guaranteed that coroutine launched through runBlocking will always execute on the same thread (i.e. thread on which runBlocking started executing) ?

1st println will show say Thread t1. But after the suspend function delay is executed, I want to know will this coroutine resume in same Thread t1 or is it possible to be executed on different thread Thread t2 ? This is because a coroutine can be executed on 2 or more threads so the coroutine created by runBlocking can execute on thread t1 and get suspended on delay() and resume on different thread t2.

fun main(): Unit = runBlocking(Dispatchers.Default) { // Thread t1
  println("runBlocking start: ${Thread.currentThread().name}") // Thread t1

  delay(3000)

  println("runBlocking end: ${Thread.currentThread().name}") // is it necessary to be t1 ?
}

The output I am getting every time is(but I feel that in 2nd line of output it could also have been DefaultDispatcher-worker-2):--

runBlocking start: DefaultDispatcher-worker-1

runBlocking end: DefaultDispatcher-worker-1


Solution

  • Yes, as long as you specify a multi-threaded dispatcher like Dispatchers.Default.

    Try launching a new coroutine or two inside runBlocking:

    fun log(msg: String) = println("[${Thread.currentThread().name}] $msg")
    
    fun main(): Unit = runBlocking(Dispatchers.Default) {
      log("runBlocking start")
      async { delay(50) }.await()
      log("runBlocking end")
    }
    

    Eventually, different threads will be printed:

    [DefaultDispatcher-worker-1 @coroutine#1] runBlocking start
    [DefaultDispatcher-worker-2 @coroutine#1] runBlocking end