gildor
12/13/2017, 2:50 AMasync { /* some blocking call */ }
is not a good idea.
because async
(and other coroutine builders) by default use CommonPool.
And CommonPool is thread pool with cpuCount - 1
threads and used everywhere.
Imagine situation, when you run commonPoolSize + 1
coroutines that block threads
In this case no one can run anything, even just process non-blocking callbacks
so, with CommonPool you should use only non-blocking api.
If some part of your code is uses blocking api, like io/networking and you don’t have replacement for that, then you can just create separate coroutine dispatcher, backed by another thread pool (you can use newFixedThreadPoolContext()
from kotlinx.coroutines, or convert any existing thread pool to coroutines context).
And use this dispatcher to access some blocking API
for example:
val DbPool = newFixedThreadPoolContext(DB_POOL_SIZE)
suspend fun sqlQuery(query: String): DbResult {
return run(DbPool) { blockingSqlQuery(query) }
}
In this case you have limited pool of threads for database, not real non-blocking, but safe to use non-blocking for client API