I have problems understanding the cancellation behavior with blocking APIs. Let me start with an easy non-blocking example that I do understand:
fun execute(job: Job) = produce<String>(CommonPool + job) {
println("a")
send("Start")
println("b")
delay(1000L) // <--- will exit here
println("c")
send("Delay done")
println("d")
send("Task done")
println("e")
}
fun main(args: Array<String>) = runBlocking<Unit> {
val job = Job()
execute(job).consumeEach {
println(it)
job.cancel()
}
}
This prints:
a
b
Start
Which is what I expect. I often have to use blocking APIs though, so let’s replace delay
with Thread.sleep
in the above example. This will print:
a
b
Start
c
d
Delay done
As expected, the blocking Thread.sleep
can’t be cancelled which is fine. But why does it execute send("Delay done")
and event print d
?
I’d expect that the send
would not execute and that the console would look like this:
a
b
Start
c
What is the intention behind this behavior?