Consider this Kotlin coroutine code snippet. What will it print?
import kotlinx.coroutines.* fun main() = runBlocking { launch(Dispatchers.Main) { println("Running on Main: ${Thread.currentThread().name}") } launch(Dispatchers.IO) { println("Running on IO: ${Thread.currentThread().name}") } launch(Dispatchers.Default) { println("Running on Default: ${Thread.currentThread().name}") } }
Remember that Dispatchers.Main runs on the main thread, while Dispatchers.IO and Dispatchers.Default use background threads.
Dispatchers.Main runs on the main thread (usually named "main"), while Dispatchers.IO and Dispatchers.Default run on background threads named like "DefaultDispatcher-worker-*".
What will happen when running this Kotlin coroutine code on a plain JVM (no Android)?
import kotlinx.coroutines.* fun main() = runBlocking { launch(Dispatchers.Main) { println("Hello from Main") } }
Think about whether Dispatchers.Main is supported outside Android or JavaFX environments.
Dispatchers.Main requires a platform-specific main thread dispatcher. On plain JVM without such support, it throws an IllegalStateException.
Analyze the output of this Kotlin coroutine code snippet:
import kotlinx.coroutines.* fun main() = runBlocking { val job = launch(Dispatchers.Default) { println("Default start: ${Thread.currentThread().name}") withContext(Dispatchers.IO) { println("Inside IO: ${Thread.currentThread().name}") } println("Back to Default: ${Thread.currentThread().name}") } job.join() }
Remember that withContext switches the coroutine context temporarily.
The coroutine starts on Default dispatcher thread, switches to IO dispatcher thread inside withContext, then returns to the original Default dispatcher thread.
What error will this Kotlin code produce?
import kotlinx.coroutines.* fun main() = runBlocking { launch(Dispatchers.Main.immediate) { println("Running immediate on Main") } }
Consider if the Main dispatcher module is included in your project.
If the Main dispatcher module is missing, using Dispatchers.Main.immediate throws IllegalStateException.
Choose the best dispatcher for CPU-heavy computations and explain why.
Think about thread pool size and task type for CPU-bound work.
Dispatchers.Default is designed for CPU-intensive tasks with a shared thread pool sized to the number of CPU cores, providing efficient parallelism.