Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interrupts, shutdown method and ExecutorService

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.

like image 614
Rollerball Avatar asked Jul 24 '13 09:07

Rollerball


2 Answers

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

like image 145
Evgeniy Dorofeev Avatar answered Sep 22 '22 02:09

Evgeniy Dorofeev


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:

  • Java Concurrency in Practice by Brian Goetz is an excellent read.
  • http://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html
like image 42
Jatin Avatar answered Sep 22 '22 02:09

Jatin