Skip to content

Instantly share code, notes, and snippets.

@twyatt
Last active March 22, 2018 00:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save twyatt/c51f81d763a6ee39657233fa725f5435 to your computer and use it in GitHub Desktop.
Save twyatt/c51f81d763a6ee39657233fa725f5435 to your computer and use it in GitHub Desktop.
Testing Kotlin Coroutines when using `newSingleThreadContext` (Thread is not being cleaned up)
import kotlinx.coroutines.experimental.channels.actor
import kotlinx.coroutines.experimental.channels.consumeEach
import kotlinx.coroutines.experimental.newSingleThreadContext
import kotlinx.coroutines.experimental.runBlocking
val threads: Set<Thread>
get() = Thread.getAllStackTraces().keys
val threadNames: List<String>
get() = threads.map { it.name }
fun main(args: Array<String>) = runBlocking {
println("threads = $threadNames")
val actor = actor<Int>(newSingleThreadContext("TestThread")) {
println("actor start")
consumeEach { item ->
println("item = $item")
}
println("actor end")
}
println("threads = $threadNames")
println("actor.close()")
actor.close()
println("threads = $threadNames")
println("thread sleep")
Thread.sleep(2_000L)
println("threads = $threadNames")
}
threads = [Signal Dispatcher, Reference Handler, Finalizer, main, Monitor Ctrl-Break]
actor start
threads = [TestThread, Signal Dispatcher, Reference Handler, Finalizer, main, Monitor Ctrl-Break]
actor.close()
actor end
threads = [TestThread, Signal Dispatcher, Reference Handler, Finalizer, main, Monitor Ctrl-Break]
thread sleep
threads = [TestThread, Signal Dispatcher, Reference Handler, Finalizer, main, Monitor Ctrl-Break]
@twyatt
Copy link
Author

twyatt commented Mar 21, 2018

Per @elizarov in #coroutines at https://kotlinlang.slack.com/:

You have explicitly close the context to release the thread for now. In the future this will not be needed, though (see Kotlin/kotlinx.coroutines#261)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment