What will be the output of this Kotlin coroutine code snippet?
import kotlinx.coroutines.* fun main() = runBlocking { launch { println("Start delay") delay(100) println("End delay") } launch { println("Start sleep") Thread.sleep(100) println("End sleep") } }
Remember that delay is a suspending function that doesn't block the thread, while Thread.sleep blocks the thread.
The delay call suspends the coroutine but allows other coroutines to run, so both "Start delay" and "Start sleep" print immediately. The Thread.sleep blocks the thread, so "End sleep" prints before "End delay".
Which reason best explains why delay is preferred over Thread.sleep in Kotlin coroutines?
Think about how blocking affects other coroutines running on the same thread.
delay suspends the coroutine but frees the thread to run other coroutines, improving concurrency. Thread.sleep blocks the thread, stopping all coroutines on it.
What will happen when running this Kotlin code?
import kotlinx.coroutines.* fun main() = runBlocking { launch(Dispatchers.Default) { println("Before sleep") Thread.sleep(500) println("After sleep") } launch(Dispatchers.Default) { repeat(3) { println("Working $it") delay(200) } } }
Consider how Thread.sleep blocks the thread and how many threads the Default dispatcher uses.
Thread.sleep blocks one thread in the Default dispatcher, but other threads run the second coroutine printing "Working" messages concurrently.
What is the output of this Kotlin coroutine code?
import kotlinx.coroutines.* fun main() = runBlocking { launch { println("Start outer") delay(100) launch { println("Start inner") Thread.sleep(100) println("End inner") } println("End outer") } }
Remember that launch starts a new coroutine immediately but does not block the parent coroutine.
The outer coroutine prints "Start outer", then delays. After delay, it launches the inner coroutine and immediately prints "End outer". The inner coroutine runs separately, printing "Start inner" and "End inner" after sleeping.
In Kotlin coroutines, why can using Thread.sleep inside a coroutine running on Dispatchers.Unconfined or a single-threaded dispatcher cause starvation of other coroutines?
Think about what happens when the only thread available is blocked.
Thread.sleep blocks the thread it runs on. If the dispatcher uses a single thread, blocking it stops all coroutines scheduled on that thread, causing starvation. delay suspends without blocking, avoiding this problem.