Last active
December 30, 2020 22:28
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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