My loose understanding is that limited parallelism...
# squarelibraries
k
My loose understanding is that limited parallelism doesn't reserve a thread of execution, it just ensures that coroutines dispatched to it only run on a limited number of threads. A new single threaded dispatcher has a dedicated thread. This is important for a SQLite writer because you want the lock held by sqlite to remain on a single thread. Limited parallelism doesn't guarantee you a reserved thread like the other approach does. So you could potentially still be dealing with SQLite writer thread lock contention.
👍 3
k
A new single threaded dispatcher has a dedicated thread.
Is this still true even if a dispatcher is “created” as a top level field?
Copy code
val Dispatchers.DatabaseIO: CoroutineContext
  get() = databaseIO + CoroutineName("DatabaseIO")

private val databaseIO: CoroutineDispatcher = Dispatchers.IO.limitedParallelism(1)
k
I’m advocating against
limitedParallelism
. I’m talking about using
newSingleThreadedContext
https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/new-single-thread-context.html
k
Sorry I meant this line actually:
Limited parallelism doesn’t guarantee you a reserved thread like the other approach does.
k
My understanding is that
limitedParallelism
will maintain it’s own internal
n
worker queues which then delegate to the underlying dispatcher for running. https://github.com/Kotlin/kotlinx.coroutines/blob/master/kotlinx-coroutines-core/common/src/internal/LimitedDispatcher.kt#L47-L51 This does not guarantee that tasks are running on the same thread; this guarantees that no more than
n
tasks will be dispatched to the wrapped dispatcher in parallel.
nod 1
To be even more clear that that: It maintains a single queue of tasks to be executed. It will maintain an atomic number of tasks which are currently being executed. It will increment and decrement them appropriately when tasks start and finish. All the while tasks are being delegated to the wrapped dispatcher with no regard for thread affinity.
👍 1
👌 1