https://kotlinlang.org logo
#coroutines
Title
# coroutines
c

christophsturm

06/08/2021, 1:18 PM
if i run this code:
Copy code
suspend fun main() {
    val executorService = Executors.newWorkStealingPool(1000)
    withContext(executorService.asCoroutineDispatcher()) {
        repeat(1000) {
            async {
                delay(1000)
            }
        }
    }
    println(executorService)
}
at the end the executor service has one task left:
java.util.concurrent.ForkJoinPool@5079ec1[Running, parallelism = 1000, size = 70, active = 1, running = 1, steals = 2000, tasks = 0, submissions = 0]
why is that. if i do runBlocking instead of withContext the executor service is empty as expected.
i reduced it to this:
Copy code
suspend fun main() {
    val executorService = Executors.newWorkStealingPool(1000)
    println(withContext(executorService.asCoroutineDispatcher()) {
        coroutineContext[Job].also { println(it) }
    })
    println(executorService)
    executorService.awaitTermination(1000, TimeUnit.SECONDS)
}
which outputs:
Copy code
DispatchedCoroutine{Active}@5672b8b6
DispatchedCoroutine{Completed}@5672b8b6
java.util.concurrent.ForkJoinPool@7649bfd7[Running, parallelism = 1000, size = 1, active = 1, running = 1, steals = 0, tasks = 0, submissions = 0]
2 Views