Can Korkmaz
02/14/2022, 8:50 AMJoffrey
02/14/2022, 9:00 AMnewSingleThreadContext creates a thread for the coroutine to run. A dedicated thread is a very expensive resource. In a real application it must be either released, when no longer needed, using the close function, or stored in a top-level variable and reused throughout the application.(docs: https://kotlinlang.org/docs/coroutine-context-and-dispatchers.html#dispatchers-and-threads)
newSingleThreadContext can be used at any other part of the programThat's not true, it's actually the crux of the problem. The doc is referring to using
launch(newSingleThreadContext(...))
directly, without storing the context in a variable. This means it cannot be referenced anywhere else, and so it can't be reused by any other coroutine than the launched one and its children. It also means you have no way to close the associated resources, because you don't have any handle to do so. So if you run this code several times, you would be creating one thread each time, and never close it. Even if you did close it properly, creating and destroying threads is expensive as opposed to just reusing a thread pool and the threads inside.
Why would it be more expensive than dispatching it at any other thread, such as main or default, or ioIt's not more expensive in itself, but those other dispatchers are public and thus reusable between coroutines, while using
newSingleThreadContext
would create a new non-shared thread every time it's used.Can Korkmaz
02/14/2022, 10:43 AM