Spot the bug
The job is cancelled after 1 second, but the work runs to the end. Which line is the problem?
val job = scope.launch(Dispatchers.Default) {var total = 0Lfor (i in 1..5_000_000_000L) {total += i % 7}log("total $total")}delay(1_000)job.cancel()
Hint 1 of 2
Where would a CancellationException be thrown?
Hint 2 of 2
Does anything in the loop suspend?
Choose an answer, then open Show answer below to check it.
Show answer
- Answer: line 3
for (i in 1..5_000_000_000L) {
The loop never suspends or checks for cancellation, so the cancel flag is never read. Add ensureActive() every so often inside the loop.