Issue
Short requirement: have ability to create corotine context, which will executed in the single thread only (e.g. without parallelism).
Additional requirement: it is better to use existing CommonPool (e.g. Thread Pool) for these tasks
Actually kotlin coroutines have method newSingleThreadContext which will create separate thread and schedule all tasks into it. However, this is dedicated thread, so ~1000 such contexts will require a lot of resources.
Therefore, I'd like to have context with the following characteristics:
- Maximum one task can be executed at the same time
- This context should reuse any other (e.g. parent context). E.g context should hold no additional threads
Solution
Starting from the 1.6.0 version of the kotlinx.coroutines library we can use limitedParallelism function on the CoroutineDispatcher object, which lets you limit parallelism without creating additional thread pools and provides a unified way to create dispatchers for unbound parallelism.
Example of usage:
class UserRepository {
private val dbDispatcher = Dispatchers.IO.limitedParallelism(1)
suspend fun getUserById(userId: Int): User? = withContext(dbDispatcher) {
executeQuery("SELECT * FROM users WHERE id = $1", userId).singleOrNull()
}
}
limitedParallelism(1) guarantees the parallelism restriction - at most 1 coroutine can be executed concurrently in this dispatcher.
It should solve the problem:
Maximum one task can be executed at the same time.
Answered By - Sergey
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.