Why does this program not terminate? `suspend fun...
# coroutines
a
Why does this program not terminate?
suspend fun main() = withContext(Executors.newSingleThreadExecutor().asCoroutineDispatcher()) {}
Even if I call cancel() from within the withContext block, I see an exception logged, but the program just hangs.
o
probably the thread never gets spun down, and it's not a daemon thread, so JVM can't exit
👍 1
d
Read API docs for newSingleThreadExecutor about whether thread is daemon or not
👍 1
t
a
Thanks @Thiyagu!
close()
worked
👍 1
Interestingly, the thread is created with a default thread factory, which according to https://github.com/openjdk-mirror/jdk7u-jdk/blob/f4d80957e89a19a29bb9f9807d2a28351ed7f7df/src/share/classes/java/util/concurrent/ThreadPoolExecutor.java#L103 suggests it's not a daemon thread.
OK, confusingly, if I supply my own factory that creates a daemon thread, it exists without extra action. This aligns with that
ThreadPoolExecutor
javadoc saying that by default, the thread is not a daemon, but it's surprising because I'd think a "daemon" would need to be explicitly exited.
d
No it's the other way around.
a
Ah, https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#setDaemon(boolean) welp there you go. Thank you everyone for your help!
t
You can always provide your
ThreadFactory
implementation to the executor.
l
The code from the original snippet should be replaced by
fun main() = runBlocking { ... }
to it doesn't waste a bunch of threads (namely, the JVM main thread and the threads from Dispatchers.Default).
a
Ah cool, thank you Louis!