Understanding Thread Count In Kotlin Flow With Suspend And runBlocking

Hey, I’m trying the new Kotlin Flows experimental API and write a simple example by following this link.

@ExperimentalCoroutinesApi
val ints: Flow<Int> = flow {
    for (i in 0..5) {
        delay(100)
        println(message = "Emitting data $i -> $coroutineContext")
        emit(i)
    }
}.catch {
    println("Exception caught -> $coroutineContext")
    return@catch this.emitAll(flowOf(103, 104, 105))
}

@ExperimentalCoroutinesApi
suspend fun main() {
    val time = measureTimeMillis {
        ints.buffer().onCompletion {
            println("completed with thread $coroutineContext")
        }.collect {
            delay(100)
            println("$coroutineContext  -> $it")
        }
    }
    val time2 = measureTimeMillis {
        ints.buffer().onCompletion {
            println("completed2 with thread $coroutineContext")
        }.collect {
            delay(100)
            println("$coroutineContext  2 -> $it")
       }
   }
   println("Number of thread use -> ${Thread.activeCount()}")
   println("Executed time -> ${time + time2} ms")
}

Now if I try to run the above code it uses 13 threads count but if I change the suspend main fun to fun main = runBlocking the program uses 2 threads.

I’m using a xeon processor with 6 cores and 32Gb ram.

Can someone please explain to me what’s happening here. Thanks in advance.

runBlocking defines an event loop Dispatcher (https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/run-blocking.html), so only one thread was used.
If Dispatcher is missing, the default one is used (the suspend fun main case).

So, I understand that runBlocking defines a CoroutineDispatcher and block the thread until it’s completion. Please correct me if I’m wrong here, the reason that runBlocking uses only 2 thread is that one coroutine is the actual used by run-blocking and one a new created when I called buffer method on Flow.

But I still don’t understand why my program uses 13 threads when I run the program suspend main fun.

@ahsansaeed067 you should inspect the thread names to deep into this question.

You can start using VisualVM or a simple kill -3 javaPid.