Почему не запускается блок блокировки с newSingleThreadExecutor? - PullRequest
0 голосов
/ 20 марта 2020

Я пытаюсь выяснить, почему этот код не работает бесконечно:

fun main() = runBlocking {
launch {
    delay(200L)
    println("Task from runBlocking $coroutineContext")
}

//    coroutineScope { // if I uncomment this line and comment next line, then it will finish
CoroutineScope(Executors.newSingleThreadExecutor().asCoroutineDispatcher()).launch {
    launch {
        delay(500L)
        println("Task from nested launch $coroutineContext")
    }

    delay(100L)
    println("Task from coroutine scope $coroutineContext")
}

println("Coroutine scope is over")
}

Когда я запускаю этот код, я вижу этот вывод:

Coroutine scope is over
Task from coroutine scope [StandaloneCoroutine{Active}@5287ba83, java.util.concurrent.Executors$FinalizableDelegatedExecutorService@91445f6]
Task from runBlocking [StandaloneCoroutine{Active}@28ac3dc3, BlockingEventLoop@32eebfca]
Task from nested launch [StandaloneCoroutine{Active}@702cf19c, java.util.concurrent.Executors$FinalizableDelegatedExecutorService@91445f6]

но программа никогда не заканчивается ... Как я писал в комментарии, если я заменю строку newSingleThreadExecutor просто простой coroutineScope, то она завершится быстро.

Почему этот код не заканчивается?

1 Ответ

0 голосов
/ 20 марта 2020

Причина этого в том, что потоки, не являющиеся демонами, поддерживают JVM.

Вам необходимо выключить ExecutorService, чтобы JVM закончила окончательно sh его выполнение.

Здесь ответили: ExecutorService JVM не завершается

...