https://kotlinlang.org logo
#coroutines
Title
# coroutines
j

Jimmy Alvarez

08/12/2021, 3:12 AM
Hello guys, hope you are doing good. This questions is kind of beginner level but I’m trying to understand a lil how concurrency works in coroutines. In this example i want to lunch 2 coroutines concurrently like this:
Copy code
coroutineScope.launch {
   // some work 
}

coroutineScope.launch {
   // some other work 
}
In my understanding, this should not block the thread given i’m launching both coroutines concurrently. but what is happening is that first coroutine blocks the thread so the second coroutine never gets executed. The only way I could make it run concurrently was to wrap
// Some work
into a
suspend
function, then I got the concurrent execution Could you explain a little why this only work by using the suspend function inside coroutine?
a

Antanas A.

08/12/2021, 7:05 AM
Hi, you are saying that you have some long working non-suspendable function in "//some work" which runs cpu intensive computations or blocks thread due I/O operations? If yes, then you must avoid that kind of calls inside coroutines because you will exhaust dispatcher's thread pool on which coroutines are executed. Proper solution would be to wrap your "cpu intensive/blocking work" in other coroutine by using:
withContext(<http://Dispatchers.IO|Dispatchers.IO>) { ... // some work }
in production env it's better to have some dedicated dispatcher with fixed thread pool for that kind of work, e.g.:
val blockingTaskDispatcher = Executors.newFixedThreadPool(32).asCoroutineDispatcher()
when use:
coroutineScope.launch {
withContext(blockingTaskDispatcher) {
// work here
}
}
and use it instead of Dispatchers.IO, because its thread pool is elastic and can span unlimited number of threads until memory overflow 🙂
👍 1
j

Jimmy Alvarez

08/12/2021, 7:13 PM
Hi Antanas, thanks for your response. I have a question, what do you mean as a
non-suspensable
function?
You’r right, the computation blocks due to I/O operations.
4 Views