2

I'm writing a scheduler which accepts a Runnable which is either queued for synchronous or asynchronous execution.

I would like to be able to implement a SomeScheduler.interrupt(int taskId) which causes a InterruptedException() to be thrown from within the thread.

Is this possible or am I going about this all wrong?

Zhro
  • 2,546
  • 2
  • 29
  • 39
  • i think with `sleep` method – uzaif Jun 27 '16 at 02:50
  • 1
    Are you using submit() or execute()? Have a look at this question: http://stackoverflow.com/questions/3929342/choose-between-executorservices-submit-and-executorservices-execute/35424481#35424481. Future.get() is useful to get InterruptedExeception and take corrective action. – Ravindra babu Jun 27 '16 at 09:37

1 Answers1

2

Threads can be interrupted, a Runnable is just class that implements the run method.
On it's own it doesn’t belong to a thread, if you want to interrupt the execution of the runnable you need to interrupt it's calling thread.
The typical way this is done is to use an ExecutorService. When you submit a runnable or callable to the executor service it will return a Future you can then interrupt a particular task by using the Future#cancel method.
Note that simply interrupting the thread doesn’t cause InterruptedException to be thrown unless the thread is running code that checks the interrupt status and throws InterruptedException, for example the Thread#sleep method.

Magnus
  • 7,952
  • 2
  • 26
  • 52
  • 1
    but you cannot do that since runnable does not have it in it's signature – Andrii Plotnikov Jan 09 '18 at 08:50
  • @Sarief Runnable does not have what in it's signature? – Magnus Jan 10 '18 at 02:30
  • It does not have InterruptedException. Since it's checked -> you cannot add it to signature. – Andrii Plotnikov Jan 10 '18 at 12:27
  • Ah right, I see what you mean. The InteruptedException doesn't need to bubble out of the Runnable, it just needs to stop running. The code in the Runnable needs to either manually check the state of `Thread#interrupted()` and halt/return when it encounters it or utilise a method like `Thread#sleep` that does this automatically. Since you cant throw the exception out of the runnable, you can catch it, and either simply `return` or rethrow as a runtime exception, doesn't really matter, so long as you end the thread. – Magnus Jan 10 '18 at 22:29
  • 1
    yup, but that is what OP is asking about – Andrii Plotnikov Jan 12 '18 at 08:41