https://kotlinlang.org logo
#coroutines
Title
# coroutines
d

David Glasser

03/26/2020, 5:51 PM
ok i swear i knew the answer to this one but — if I want to run some Java function that blocks and might be slow and get a timeout from it, how do I do that? will this do the trick?
Copy code
withTimeout(5000L) {
  withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
    somePotentiallySlowThreadBlockingFunction()
  }
}
Note that I'm perfectly fine with the fact that the timeout won't actually stop the work from happening in
somePotentiallySlowThreadBlockingFunction
. This is happening at global process shutdown so the important thing is being able to move on to the next step of shutdown in finite time, not absolutely making sure that
somePotentiallySlowThreadBlockingFunction
doesn't continue. Like, I know
withTimeout
alone won't work with non-cooperative code, but does the withContext maybe make it work?
OK, testing shows the answer is no. So I guess my question is, what's the coro-correct way to "run X in the background, wait for it to stop but with a timeout"? Job.join doesn't have a timeout...
ah ok, stackoverflow is my friend as always.
withTimeout(timeout) { d.await() }
2 Views