custom-scope-with-async
custom scope - with await - exception from the co-routine will be rethrown parent when we await, BUT siblings are cancelled RIGHT away when uncaught exception happens.
Code
package com.glassthought.sandbox
import gt.sandbox.util.output.Emojis
import gt.sandbox.util.output.Out
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.runBlocking
import kotlin.system.exitProcess
import kotlin.time.Duration.Companion.seconds
fun main(): kotlin.Unit = runBlocking {
val out = Out.standard()
out.info("START")
try {
val myScope = CoroutineScope(
Dispatchers.Default
)
val coRoutine1Deferred = myScope.async(
CoroutineName("WillFail")
) {
val timeMillis = 1000L
out.info("This one will throw in $timeMillis ms")
delay(timeMillis)
val exc = MyExceptionWillThrowFromCoroutine("I-Failed-In-CoRoutine")
out.warn("${Emojis.EXCEPTOIN} I am throwing [${exc::class.simpleName}/${exc.message}]! ${Emojis.EXCEPTOIN}")
throw exc
"ResultFromWillFail"
}
val coRoutine2Deferred = myScope.async(CoroutineName("JustPrints")) {
(0..10)
.map { "a-${it}" }
.forEach {
out.info(it)
try {
delay(500)
} catch (e: CancellationException) {
val excMsg = e.message ?: e.toString()
out.warn("${Emojis.OBIDIENT} I have caught [${e::class.simpleName}/$excMsg], and rethrowing it ${Emojis.OBIDIENT} ")
throw e
}
}
}
out.actionWithMsg(
actionThatWeAreDelayingFor = "coRoutine1Deferred.join()",
action = {
coRoutine1Deferred.join()
}
)
out.infoPrintState(coRoutine1Deferred, "coRoutine1Deferred")
out.info("myScope.isActive = ${myScope.isActive}")
out.delayedActionWithMsg(
actionThatWeAreDelayingFor = "coRoutine1Deferred.await()",
delayBeforeAction = 2.seconds,
action = {
out.info("coRoutine1Deferred.await()=[${coRoutine1Deferred.await()}]")
}
)
out.delayedActionWithMsg(
actionThatWeAreDelayingFor = "coRoutine2Deferred.await()",
delayBeforeAction = 2.seconds,
action = {
out.info("coRoutine1Deferred.await()=[${coRoutine2Deferred.await()}]")
}
)
} catch (e: Exception) {
out.error("in main got an exception! of type=[${e::class.simpleName}] with msg=[${e.message}] cause=[${e.cause}]. Exiting with error code 1")
exitProcess(1)
}
out.info("DONE - without errors on main")
}
class MyExceptionWillThrowFromCoroutine(msg: String) : RuntimeException(msg)
Command to reproduce:
gt.sandbox.checkout.commit 17ff993a20b91dfff9ea \
&& cd "${GT_SANDBOX_REPO}" \
&& cmd.run.announce "./gradlew run --quiet"
Recorded output of command:
Picked up JAVA_TOOL_OPTIONS: -Dkotlinx.coroutines.debug
Picked up JAVA_TOOL_OPTIONS: -Dkotlinx.coroutines.debug
[INFO][elapsed: 14ms][š„][ā ][coroutname:@coroutine#1][tname:main/tid:1] START
[INFO][elapsed: 33ms][2ļøā£][ā¶][coroutname:@WillFail#2][tname:DefaultDispatcher-worker-1/tid:31] This one will throw in 1000 ms
[INFO][elapsed: 35ms][š„][ā ][coroutname:@coroutine#1][tname:main/tid:1] Performing action=[coRoutine1Deferred.join()]
[INFO][elapsed: 37ms][3ļøā£][ā·][coroutname:@JustPrints#3][tname:DefaultDispatcher-worker-2/tid:32] a-0
[INFO][elapsed: 538ms][3ļøā£][ā·][coroutname:@JustPrints#3][tname:DefaultDispatcher-worker-2/tid:32] a-1
[INFO][elapsed: 1039ms][2ļøā£][ā·][coroutname:@JustPrints#3][tname:DefaultDispatcher-worker-1/tid:31] a-2
[WARN][elapsed: 1068ms][3ļøā£][ā¶][coroutname:@WillFail#2][tname:DefaultDispatcher-worker-2/tid:32] š„ I am throwing [MyExceptionWillThrowFromCoroutine/I-Failed-In-CoRoutine]! š„
[INFO][elapsed: 1070ms][š„][ā ][coroutname:@coroutine#1][tname:main/tid:1] Performed action=[coRoutine1Deferred.join()]
[INFO][elapsed: 1073ms][š„][ā ][coroutname:@coroutine#1][tname:main/tid:1] State of [coRoutine1Deferred]:
coRoutine1Deferred.isActive | false
coRoutine1Deferred.isCancelled | true
coRoutine1Deferred.isCompleted | true
[INFO][elapsed: 1073ms][š„][ā ][coroutname:@coroutine#1][tname:main/tid:1] myScope.isActive = false
[INFO][elapsed: 1076ms][š„][ā ][coroutname:@coroutine#1][tname:main/tid:1] 2s delay, before_action=[coRoutine1Deferred.await()]
[WARN][elapsed: 1083ms][2ļøā£][ā·][coroutname:@JustPrints#3][tname:DefaultDispatcher-worker-1/tid:31] š«” I have caught [JobCancellationException/Parent job is Cancelling], and rethrowing it š«”
[INFO][elapsed: 3077ms][š„][ā ][coroutname:@coroutine#1][tname:main/tid:1] Done with=2s delay performing action=[coRoutine1Deferred.await()]
[ERROR][elapsed: 3079ms][š„][ā ][coroutname:@coroutine#1][tname:main/tid:1] in main got an exception! of type=[MyExceptionWillThrowFromCoroutine] with msg=[I-Failed-In-CoRoutine] cause=[com.glassthought.sandbox.MyExceptionWillThrowFromCoroutine: I-Failed-In-CoRoutine]. Exiting with error code 1
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:run'.
> Process 'command '/home/nickolaykondratyev/.jdks/corretto-21.0.7/bin/java'' finished with non-zero exit value 1
* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
> Get more help at https://help.gradle.org.
BUILD FAILED in 3s
Also see:
From ā ļø Unhandled exception from async can go to parent scope without going through await() ā ļø
Go to text ā
Uncaught exception behavior with async
:
- IF
await()
is called before theasync
coroutine fails.- THEN: the exception goes through
await()
- THEN: the exception goes through
- IF the
async
coroutine fails beforeawait()
is called.- THEN: the exception propagates up the Job hierarchy immediately.
As we would expect example: exception goes through await()
Here we observe await() receiving exception
Code
package com.glassthought.sandbox
import com.glassthought.sandbox.util.out.impl.out
import gt.sandbox.util.output.Emojis
import gt.sandbox.util.output.Out
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlin.system.exitProcess
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
private suspend fun mainImpl(out: Out) {
coroutineScope {
foo("msg-1")
}
}
private suspend fun foo(msg: String) {
out.actionWithMsg("fooImpl", { fooImpl(msg) })
}
private suspend fun fooImpl(msg: String) {
coroutineScope {
launch {
out.delayNamed(3.seconds, "delayed([${msg}])")
}
launch {
out.delayNamed(2.seconds, "delayed([${msg}])")
}
val deferred = async {
out.delayNamed(500.milliseconds, "delayed([${msg}])")
throw MyRuntimeException.create("exception-from-async", out)
}
out.info("Just launched co-routines. Going into deferred.await()")
// This code is unreachable since async exception will go to the parent instead of
// going to the await()
try {
deferred.await()
} catch (e: Exception) {
out.error("[RETHROWING][${Emojis.CAUGHT_EXCEPTION}] Caught exception on [deferred.await()] from async: ${e.message} of type [${e::class.simpleName}]")
throw e
}
}
}
fun main(): Unit = runBlocking {
out.info("START - ON MAIN")
try {
mainImpl(out)
} catch (e: Exception) {
out.error("back at MAIN got an exception! of type=[${e::class.simpleName}] with msg=[${e.message}] cause=[${e.cause}]. Exiting with error code 1")
exitProcess(1)
}
out.info("DONE - WITHOUT errors on MAIN")
}
Command to reproduce:
gt.sandbox.checkout.commit fa1ebcc936a485d23912 \
&& cd "${GT_SANDBOX_REPO}" \
&& cmd.run.announce "./gradlew run --quiet"
Recorded output of command:
Picked up JAVA_TOOL_OPTIONS: -Dkotlinx.coroutines.debug
Picked up JAVA_TOOL_OPTIONS: -Dkotlinx.coroutines.debug
[INFO][elapsed: 15ms][š„][ā ][coroutname:@coroutine#1][tname:main/tid:1] START - ON MAIN
[INFO][elapsed: 31ms][š„][ā ][coroutname:@coroutine#1][tname:main/tid:1] [>] Starting action=[fooImpl]
[INFO][elapsed: 34ms][š„][ā ][coroutname:@coroutine#1][tname:main/tid:1] Just launched co-routines. Going into deferred.await()
[INFO][elapsed: 38ms][š„][ā¶][coroutname:@coroutine#2][tname:main/tid:1] Delaying for 3s what_for=[delayed([msg-1])]
[INFO][elapsed: 39ms][š„][ā·][coroutname:@coroutine#3][tname:main/tid:1] Delaying for 2s what_for=[delayed([msg-1])]
[INFO][elapsed: 39ms][š„][āø][coroutname:@coroutine#4][tname:main/tid:1] Delaying for 500ms what_for=[delayed([msg-1])]
[INFO][elapsed: 541ms][š„][āø][coroutname:@coroutine#4][tname:main/tid:1] Done delaying for 500ms what_for=[delayed([msg-1])]
[WARN][elapsed: 571ms][š„][āø][coroutname:@coroutine#4][tname:main/tid:1] š„ throwing exception=[MyRuntimeException] with msg=[exception-from-async]
[WARN][elapsed: 591ms][š„][ā¶][coroutname:@coroutine#2][tname:main/tid:1] š«” I have caught [JobCancellationException/Parent job is Cancelling], and rethrowing it š«”
[WARN][elapsed: 592ms][š„][ā·][coroutname:@coroutine#3][tname:main/tid:1] š«” I have caught [JobCancellationException/Parent job is Cancelling], and rethrowing it š«”
[ERROR][elapsed: 593ms][š„][ā ][coroutname:@coroutine#1][tname:main/tid:1] [RETHROWING][ļæ½ Caught exception on [deferred.await()] from async: exception-from-async of type [MyRuntimeException]
[WARN][elapsed: 593ms][š„][ā ][coroutname:@coroutine#1][tname:main/tid:1] [<][š„] Finished action=[fooImpl], threw exception of type=[MyRuntimeException].
[ERROR][elapsed: 594ms][š„][ā ][coroutname:@coroutine#1][tname:main/tid:1] back at MAIN got an exception! of type=[MyRuntimeException] with msg=[exception-from-async] cause=[null]. Exiting with error code 1
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:run'.
> Process 'command '/home/nickolaykondratyev/.jdks/corretto-21.0.7/bin/java'' finished with non-zero exit value 1
* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
> Get more help at https://help.gradle.org.
BUILD FAILED in 1s
Newer behavior: exception propagates through Job link to parent scope WITHOUT going through await()
ā ļø Here we add delay() such that exception is thrown from async BEFORE we call await() on deferred object. Result: Exception goes directly to parent scope without going through await() ā ļø
Code
package com.glassthought.sandbox
import com.glassthought.sandbox.util.out.impl.out
import gt.sandbox.util.output.Emojis
import gt.sandbox.util.output.Out
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlin.system.exitProcess
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
private suspend fun mainImpl(out: Out) {
coroutineScope {
foo("msg-1")
}
}
private suspend fun foo(msg: String) {
out.actionWithMsg("fooImpl", { fooImpl(msg) })
}
private suspend fun fooImpl(msg: String) {
coroutineScope {
launch(CoroutineName("IJustDelay-3Sec-AndPrint")) {
out.delayNamed(3.seconds, "delayed([${msg}])")
}
launch(CoroutineName("IJustDelay-2Sec-AndPrint")) {
out.delayNamed(2.seconds, "delayed([${msg}])")
}
val deferred = async(CoroutineName("IAmGoingToThrow")) {
out.delayNamed(500.milliseconds, "delayed([${msg}])")
throw MyRuntimeException.create("exception-from-async", out)
}
out.info("Just launched co-routines.")
out.delayNamed(1.seconds, "Going into DELAY before calling [deferred.await()]")
// This code is unreachable since async exception will go to the parent instead of
// going to the await()
try {
out.info("About to call [deferred.await()] (WE ARE NEVER GOING TO REACH THIS LINE)")
deferred.await()
} catch (e: Exception) {
out.error("[RETHROWING][${Emojis.CAUGHT_EXCEPTION}] Caught exception on [deferred.await()] from async: ${e.message} of type [${e::class.simpleName}]")
throw e
}
}
}
fun main(): Unit = runBlocking(CoroutineName("RunBlocking-At-Main")) {
out.info("START - ON MAIN")
try {
mainImpl(out)
} catch (e: Exception) {
out.error("back at MAIN got an exception! of type=[${e::class.simpleName}] with msg=[${e.message}] cause=[${e.cause}]. Exiting with error code 1")
exitProcess(1)
}
out.info("DONE - WITHOUT errors on MAIN")
}
Command to reproduce:
gt.sandbox.checkout.commit 172df689c3cb592bc3eb \
&& cd "${GT_SANDBOX_REPO}" \
&& cmd.run.announce "./gradlew run --quiet"
Recorded output of command:
Picked up JAVA_TOOL_OPTIONS: -Dkotlinx.coroutines.debug
Picked up JAVA_TOOL_OPTIONS: -Dkotlinx.coroutines.debug
[INFO][elapsed: 15ms][š„][ā ][coroutname:@RunBlocking-At-Main#1][tname:main/tid:1] START - ON MAIN
[INFO][elapsed: 32ms][š„][ā ][coroutname:@RunBlocking-At-Main#1][tname:main/tid:1] [>] Starting action=[fooImpl]
[INFO][elapsed: 35ms][š„][ā ][coroutname:@RunBlocking-At-Main#1][tname:main/tid:1] Just launched co-routines.
[INFO][elapsed: 36ms][š„][ā ][coroutname:@RunBlocking-At-Main#1][tname:main/tid:1] Delaying for 1s what_for=[Going into DELAY before calling [deferred.await()]]
[INFO][elapsed: 39ms][š„][ā¶][coroutname:@IJustDelay-3Sec-AndPrint#2][tname:main/tid:1] Delaying for 3s what_for=[delayed([msg-1])]
[INFO][elapsed: 39ms][š„][ā·][coroutname:@IJustDelay-2Sec-AndPrint#3][tname:main/tid:1] Delaying for 2s what_for=[delayed([msg-1])]
[INFO][elapsed: 40ms][š„][āø][coroutname:@IAmGoingToThrow#4][tname:main/tid:1] Delaying for 500ms what_for=[delayed([msg-1])]
[INFO][elapsed: 541ms][š„][āø][coroutname:@IAmGoingToThrow#4][tname:main/tid:1] Done delaying for 500ms what_for=[delayed([msg-1])]
[WARN][elapsed: 572ms][š„][āø][coroutname:@IAmGoingToThrow#4][tname:main/tid:1] š„ throwing exception=[MyRuntimeException] with msg=[exception-from-async]
[WARN][elapsed: 591ms][š„][ā¶][coroutname:@IJustDelay-3Sec-AndPrint#2][tname:main/tid:1] š«” I have caught [JobCancellationException/Parent job is Cancelling], and rethrowing it š«”
[WARN][elapsed: 592ms][š„][ā·][coroutname:@IJustDelay-2Sec-AndPrint#3][tname:main/tid:1] š«” I have caught [JobCancellationException/Parent job is Cancelling], and rethrowing it š«”
[WARN][elapsed: 593ms][š„][ā ][coroutname:@RunBlocking-At-Main#1][tname:main/tid:1] š«” I have caught [JobCancellationException/ScopeCoroutine is cancelling], and rethrowing it š«”
[WARN][elapsed: 594ms][š„][ā ][coroutname:@RunBlocking-At-Main#1][tname:main/tid:1] [<][š„] Finished action=[fooImpl], threw exception of type=[MyRuntimeException].
[ERROR][elapsed: 594ms][š„][ā ][coroutname:@RunBlocking-At-Main#1][tname:main/tid:1] back at MAIN got an exception! of type=[MyRuntimeException] with msg=[exception-from-async] cause=[null]. Exiting with error code 1
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:run'.
> Process 'command '/home/nickolaykondratyev/.jdks/corretto-21.0.7/bin/java'' finished with non-zero exit value 1
* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
> Get more help at https://help.gradle.org.
BUILD FAILED in 1s
Backlinks