Andrea Giuliano
07/23/2020, 7:43 PMval myScope = CoroutineScope(Executors.newFixedThreadPool(1).asCoroutineDispatcher())
@Test
fun testCoroutines() = runBlocking<Unit>(myScope.coroutineContext) {
myScope.launch() {
println("first 1")
delay(100)
println("first 2")
}
myScope.launch() { println("second") }
}
Can someone explain to me why I will never see “first 2" printed?
if I dont use myscope.launch all works as expected and I see the 3 lines printed. That makes sense since the launch coroutines inherit the scope from runBlocking. But if I set it explicitly something changes not sure why (edited)octylFractal
07/23/2020, 7:44 PMtestCoroutines
launch
instead of prefixing it, they become children of `runBlocking`'s scope, and runBlocking
will wait for them to finish before returningZach Klippenstein (he/him) [MOD]
07/23/2020, 7:49 PMCoroutineScope
function will create a Job
for itself if the context you pass doesn’t contain one. Since you’re only passing a dispatcher, it doesn’t, so the scope will get its own job. I think this would work as expected if you only passed the dispatcher itself directly to runBlocking
, in that case runBlocking
would use its own Job
as the parent, and would be aware that there are two coroutines which need to both finish.val myContext = Executors.newFixedThreadPool(1).asCoroutineDispatcher()
@Test
fun testCoroutines() = runBlocking<Unit>(myContext) {
…
julian
07/23/2020, 8:42 PMlaunch
to prevent runBlocking
from exiting, there has to be parent-child relationships between `runBlocking`'s Job
, and the Job
of each launch
. As the code is currently written, that relationship is never established.Andrea Giuliano
07/23/2020, 8:47 PMZach Klippenstein (he/him) [MOD]
07/23/2020, 8:51 PMAndrea Giuliano
07/23/2020, 8:53 PMjulian
07/23/2020, 8:57 PM...although I'm explicitly setting runblocking they will all go in parallel no matter whatTechnically, I think even when the job hierarchy is properly established, it's still correct to say that the coroutines run concurrently, even if
runBlocking
waits for the launch
s to complete.octylFractal
07/23/2020, 9:00 PMsuspend
they can interleave with eachother.
coroutines are not always parallel, such as in the current setup displayed here. They do not always run multiple tasks at the same time, only if there are multiple threads is that possiblejulian
07/23/2020, 9:06 PM1
, so it can be concurrent, but not parallel.Andrea Giuliano
07/23/2020, 9:08 PM