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

Jonathan

09/12/2018, 2:06 PM
Can someone help me understand why I cannot replace
awaitAll(one, two)
by
one.await(); two.await()
in this code?
m

marstran

09/12/2018, 2:06 PM
What happens when you do it?
j

Jonathan

09/12/2018, 2:07 PM
it will hangs
As far as I understand, "two" reference a child job, and it should make the parent fail as soon as it throw its exception.
And as soon as the parent is failed the job "one" should be cancelled
making "one.await" throw CancelleationException
but that's not what we can observe. the job "one" doesn't seem to be cancelled, and the
one.await
hangs
v

Vsevolod Tolstopyatov [JB]

09/12/2018, 2:10 PM
it’s a tricky place and we don’t yet decided how to design it 🙂 You have three coroutines:
foo
,
one
and
two
.
async
does not cancel its parent.
foo
is waiting for
one
(which sleeps forever), while
two
already failed, but this exception is not delivered, because no one called
await
on it. Complexity behind
awaitAll
implementation is exactly to resolve this problem
👍 1
j

Jonathan

09/12/2018, 2:13 PM
ah... of course it makes sense! Thank you @Vsevolod Tolstopyatov [JB]
(my mistake was assuming
async
cancel the parent on failure)
v

Vsevolod Tolstopyatov [JB]

09/12/2018, 2:16 PM
You are welcome. The first thing which comes to mind is to cancel parent when
async
fails, but then in
Copy code
try {
async { throw MyException() }.await()
} catch (e: MyException) {
}
catch
block won’t be executed because cancellation throws
CancellationException
🙂
👍 1
but for
GlobalScope.async
catch
block will be executed and that’s where this mental model breaks 😞
c

codyoss

09/12/2018, 2:20 PM
huh, this is a little confusing. Is there a good article or any documentation that explains this more? Just trying to understand a little better….
v

Vsevolod Tolstopyatov [JB]

09/12/2018, 2:23 PM
c

codyoss

09/12/2018, 3:03 PM
ah thanks, It has been a while since I have looked at that readme. Seems like it has gotten some love recently. Thanks!
4 Views