Calling blocking code in coroutines

Cancelling a coroutine does not interrupt a thread. This is done so by design, because, unfortunately, many Java libraries incorrectly operate in interrupted threads. You can use Thread.interrupt safely only for the code that you know well / wrote yourself. It is also not a good idea to interrupt a thread that you don’t own.
Btw, java.util.concurrent.Future.cancel has a boolean mayInterruptIfRunning parameter.

If you have a piece of blocking code that you know as being well-behaved when thread interruption flag is set, you’ll have to write your own adapter to covert coroutine cancellation into thread interruption.

Having said that, it might be a desirable feature to optionally support thread interruption for newSingleThreadContext and its friends (including Executor.asCoroutineDispatcher extension), so that you can create your own context that you know is going to be used with interruptible blocking code. I’ve created the corresponding change request: Support optional thread interrupt in newSingleThreadContext as its friends · Issue #57 · Kotlin/kotlinx.coroutines · GitHub

1 Like