Directly from this java tutorial:
To support immediate shutdown, tasks should handle interrupts correctly
Would anybody be able to articulate the point? What's the relation between tasks and interrupts and the shutdown method? Does it only mean if there is a task waiting for something it must throw InterruptedException
?
Thanks in advance.
Imagine you ran this task with ExecutorService
class Task implements Runnable() {
public void run() {
while(true) {
}
}
}
now you want to shutdown the ExecutorService with shutdownNow(). ExecutorService will call interrupt() on the Thread running the task, but since the task does not respond to interrupts it will continue running and ExecutorService will never shutdown.
The following change will make this task interruptible
while(!Thread.interrupted()) {
}
and will allow ExecutorService to shutdown
What it simply means is that you timely keep checking the interrupt
status in your code. This can be checked using Thread.currentThread().isInterrupted()
.
In Java unlike other Unix calls, you only have interrupt to communicate with other thread. Hence you cannot send signals etc. If you wish to notify another thread to stop whatever it is doing as it might not be required then one of the legitimate way for communication is via interrupting that thread.
What happens when you interrupt a thread?
Every thread has a boolean internally which is false
by default. When you interrupt a thread, this boolean is set as true. So hence the documentation asks you to keep checking timely the status of the boolean. If true
, then the convention is to stop doing any task undertaken and to come out of loop or whatever.
Though interrupting
a thread is just a notification. But by convention in Java, it is taken as a request for shutdown. You can treat this interrupt
status as anything you want (ex: requesting to send mail's, take db dump etc) but it is not recommended as most of the internal java libraries are built treating it as request for shutdown.
What is InterruptedException for?
In java.util.concurrent
package, using some class if a thread gets blocked (in await
or getLock
or in blockign queue etc) and you interrupt that thread. The gets unblocked the library throws InterruptedException to notify you that the thread was blocked.
References:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With