Why doesn't this Kotlin program end?

Viewed 72

Can anyone tell me why this program doesn't finish if you run it?

import kotlinx.coroutines.*
import java.util.concurrent.Executors

fun main(args: Array<String>) {
    val dispatcher = Executors.newSingleThreadExecutor().asCoroutineDispatcher()
    val scope = CoroutineScope(dispatcher)
    scope.launch {  }
    scope.cancel()
}

I was writing a bit of database code that I wanted to dedicate a thread to and noticed this behavior. If I just use Dispatchers.IO instead of making my own then it finishes right away, but I wanted a dedicated single thread in this case.

1 Answers

Looks like @Slaw was right, it has to be manually closed. I guess its a somewhat arbitrary design choice?


import kotlinx.coroutines.*
import java.util.concurrent.Executors

fun main(args: Array<String>) {
    val dispatcher = Executors.newSingleThreadExecutor().asCoroutineDispatcher()
    val scope = CoroutineScope(dispatcher)
    scope.launch {  }
    scope.cancel()
    dispatcher.close() // missing  this
}

A bit unfortunate since the obsolete newSingleThreadContext() didn't require this.

Related