Trigger InterruptException inside a job

Many already existing JVM APIs polls in a try {} catch {} block using InterruptException to prematurely wake themselves up. What is the correct way to handle those APIs when using coroutines (eventually using JVM IO dispatcher)?
A workaround could be use a timeout version of the same API, if available, and wait again in a cycle.

In my case the blocking call is NIO WatchService.take() which waits until it got something to return or the thread is interrupted and throws the exception. I could use WatchService.poll(5, TimeUnit.SECONDS) and cycle if nothing is returned or the job is cancelled using isActive, but it feels like… wrong.

@fvasco :slight_smile:

Hi @lamba92
interrupting a thread in a thread pool is not easy (you cannot be sure to block the right code) and not pretty usefull (thread should serve for many purpose).

Can you consider to replace your code using async-NIO, or evaluate some async libraries (like JDK 11 HttpClient)?

I suggest you to consider this way or revert your code on multi-thread style, or use a dedicated thread-dispatcher for your task.

The project where i’m using it is this one, especially this file. Can you show me what you mean by async-NIO?

Hi @lamba92
I understand your problem, now.

The answer for your question is: you cannot use WatchService in asynchronous way.

The tip for your problem is: close WatchService insead of interrupt the thread, so you are free to take all events.
In such case you have to dispose the WatchService when no job is active.

Thank you :slight_smile: I did not notice the close() method! I guess this should do the trick!

So summarizing, there is no way to exploit thread interrupts when using coroutines (which is logic since many jobs shares a common pool of threads). When there is a workaround solution go for it!