Skip to content

Instantly share code, notes, and snippets.

@lgtout
Last active July 22, 2021 01:34
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 lgtout/420def74f57464c5716b3835c01d7953 to your computer and use it in GitHub Desktop.
Save lgtout/420def74f57464c5716b3835c01d7953 to your computer and use it in GitHub Desktop.
withContext cancellation
import kotlinx.coroutines.*
import java.util.concurrent.ThreadLocalRandom
fun main() {
val job = GlobalScope.launch {
Thread.sleep(1000)
try {
println(1)
withContext(CoroutineName("foo")) {
val rnd = ThreadLocalRandom.current()
val sum = (1..100_000_000).sumOf { rnd.nextInt() }
println("Same dispatcher sum = $sum")
}
} catch (e: Exception) {
println("Same dispatcher threw: $e")
throw e
}
try {
withContext(Dispatchers.IO) {
val rnd = ThreadLocalRandom.current()
val sum = (1..100_000_000).sumOf { rnd.nextInt() }
println("Changed dispatcher sum = $sum")
}
} catch (e: Exception) {
println("Changed dispatcher threw: $e")
throw e
}
}
job.invokeOnCompletion { cause -> println("job completed with $cause") }
job.cancel()
Thread.currentThread().join()
}
@lgtout
Copy link
Author

lgtout commented Jul 22, 2021

Output:

Same dispatcher threw: kotlinx.coroutines.JobCancellationException: StandaloneCoroutine was cancelled; job=StandaloneCoroutine{Cancelling}@58e9a128
job completed with kotlinx.coroutines.JobCancellationException: StandaloneCoroutine was cancelled; job=StandaloneCoroutine{Cancelled}@58e9a128

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment