Hi, I was revising coroutines and dispatchers toda...
# coroutines
c
Hi, I was revising coroutines and dispatchers today and noticed in docs that setting dispatcher with newSingleThreadContext is a very expensive operation, but I don't understand why. Why would it be more expensive than dispatching it at any other thread, such as main or default, or io. Since coroutines aren't blocking, thread allocated with newSingleThreadContext can be used at any other part of the program. If its expensiveness caused by its job being executed by a single thread concurrently, wouldn't it be at most as expensive as posix pthreads?
j
I think you might be talking about this part, right?
newSingleThreadContext 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 program
That'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 io
It'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.
👍 1
c
@Joffrey Understood, thank you.