Skip to content

Instantly share code, notes, and snippets.

@twyatt
Last active December 30, 2020 22:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save twyatt/cb05bef5756082b31d71f69e8afdc427 to your computer and use it in GitHub Desktop.
Save twyatt/cb05bef5756082b31d71f69e8afdc427 to your computer and use it in GitHub Desktop.
Experiment to confirm that multiple Coroutines will all suspend when calling `Deferred.await` (and all get the resulting failure)
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.supervisorScope
suspend fun <T> Deferred<T>.awaitCatching(launchNumber: Int, startTime: Long) = try {
await()
} catch (t: Throwable) {
val elapsed = System.currentTimeMillis() - startTime
println("launch@$launchNumber caught ${t.message} at ${elapsed / 1_000f} seconds")
}
suspend fun main() = supervisorScope<Unit> {
val start = System.currentTimeMillis()
val job = async {
delay(5_000L)
error("ouch")
}
launch(Dispatchers.IO) {
delay(500L)
job.awaitCatching(1, start)
}
launch(Dispatchers.IO) {
delay(2_500L)
job.awaitCatching(2, start)
}
launch(Dispatchers.IO) {
delay(7_000L)
job.awaitCatching(3, start)
}
}
launch@2 caught ouch at 5.059 seconds
launch@1 caught ouch at 5.059 seconds
launch@3 caught ouch at 7.056 seconds
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment