Simple usage of CoRoutines with IO Dispatcher

About

Here we show example of simple usage of dispatcher io.

We can see that different OS threads are being used.

Code

package gt.sandbox

import gt.sandbox.internal.output.Out
import kotlinx.coroutines.*

val out = Out.standard()

suspend fun fetchData(s: String) {
    out.println("Fetching data... $s")
    delay(1000) // This suspends the coroutine for 1 second without blocking the thread
    out.println("Data fetched $s")
}

fun main(): Unit = runBlocking {
    launch(Dispatchers.IO) {
        fetchData("a-1")
        fetchData("a-2")
    }
    launch(Dispatchers.IO) {
        fetchData("b")
    }
    launch(Dispatchers.IO) {
        fetchData("c")
    }
}

Command to reproduce:

gt.sandbox.checkout.commit 1fc85e0 \
&& cd "${GT_SANDBOX_REPO}" \
&& cmd.run.announce "./gradlew run"

Recorded output of command:

> Task :app:checkKotlinGradlePluginConfigurationErrors SKIPPED
> Task :app:processResources NO-SOURCE
> Task :app:compileKotlin
> Task :app:compileJava NO-SOURCE
> Task :app:classes UP-TO-DATE

> Task :app:run
[2024-06-09T04:18:21.291646Z][ms-elapsed-since-start:   50][tname:DefaultDispatcher-worker-2/tid:22] Fetching data... c
[2024-06-09T04:18:21.291456Z][ms-elapsed-since-start:   50][tname:DefaultDispatcher-worker-1/tid:21] Fetching data... a-1
[2024-06-09T04:18:21.291454Z][ms-elapsed-since-start:   50][tname:DefaultDispatcher-worker-3/tid:23] Fetching data... b
[2024-06-09T04:18:22.323347Z][ms-elapsed-since-start: 1071][tname:DefaultDispatcher-worker-2/tid:22] Data fetched c
[2024-06-09T04:18:22.323736Z][ms-elapsed-since-start: 1071][tname:DefaultDispatcher-worker-3/tid:23] Data fetched a-1
[2024-06-09T04:18:22.323347Z][ms-elapsed-since-start: 1071][tname:DefaultDispatcher-worker-1/tid:21] Data fetched b
[2024-06-09T04:18:22.324494Z][ms-elapsed-since-start: 1072][tname:DefaultDispatcher-worker-3/tid:23] Fetching data... a-2
[2024-06-09T04:18:23.325568Z][ms-elapsed-since-start: 2073][tname:DefaultDispatcher-worker-3/tid:23] Data fetched a-2

BUILD SUCCESSFUL in 2s
2 actionable tasks: 2 executed

Backlinks