Multithreading using Kotlin Coroutines

旧时模样 提交于 2019-12-06 12:46:06

If you look at the implementation of CommonPool, you'll notice that it's working on java.util.concurrent.ForkJoinPool or a thread pool with the following size:

(Runtime.getRuntime().availableProcessors() - 1).coerceAtLeast(1)

With 4 available processors, this will result in 3 which answers why you do see 3 worker threads.

The ForkJoinPool-size can be determined as follows (will be the same):

ForkJoinPool.commonPool().parallelism

Please see this answer if you work with coroutines version >= 1.0

As of Coroutines 1.0, the code will look slightly different since CommonPool will be replaced with Dispatchers.Default now:

fun main(args: Array<String>) = runBlocking {
    val cores = Runtime.getRuntime().availableProcessors()
    println("number of cores: $cores")

    val jobs = List(10) {
        async(Dispatchers.Default) {
            delay(100)
            println("async #$it on thread ${Thread.currentThread().name}")
        }
    }
    jobs.forEach { it.join() }
}

Also, you will now get the following:

It is backed by a shared pool of threads on JVM. By default, the maximal number of threads used by this dispatcher is equal to the number CPU cores, but is at least two.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!