Mikael Ståldal
09/25/2022, 8:48 AMasync { doStuff() }.await() to make the coroutine cancellable (see code/async/cancelandsuspension.kts in https://media.pragprog.com/titles/vskotlin/code/vskotlin-code.zip). Is that really a good advice? It seems like the long running blocking code is not cancelled, it is simply detached from the parent coroutine and will continue to run to completion in backround, and will block the completion of the surrounding runBlocking.
fun getResponse(ms: Int): String {
val s = URL("<http://httpstat.us/200?sleep=$ms>").readText()
println("${LocalTime.now()} Got: $s")
return s
}
suspend fun fetchResponse() = coroutineScope {
try {
println(async { getResponse(4000) }.await())
} catch (ex: CancellationException) {
println("${LocalTime.now()} fetchResponse: ${ex.message}")
}
}
fun main() {
println("${LocalTime.now()} before runBlocking")
runBlocking {
val job = launch(Dispatchers.Default) {
launch { fetchResponse() }
}
println("${LocalTime.now()} Let it run...")
delay(2000)
println("${LocalTime.now()} OK, that's enough, cancel")
job.cancel()
println("${LocalTime.now()} end of runBlocking")
}
println("${LocalTime.now()} after runBlocking")
}uli
09/25/2022, 9:49 AMephemient
09/25/2022, 11:46 AMrunInterruptible can interrupt typical Java blocking codeMikael Ståldal
09/25/2022, 7:44 PMjava.net.URL it seems.ephemient
09/25/2022, 10:37 PMThread.interrupt() which stops Thread.sleep(), lock acquisition, and some I/O. if it doesn't stop URL.getText() then there's no way of stopping it in Java eitherephemient
09/25/2022, 10:40 PMMikael Ståldal
09/26/2022, 7:31 AM