Best way to handle InterruptedException

Element picture Element · Mar 1, 2016 · Viewed 8.2k times · Source

I am using Thread.sleep(10000); hence i need to handle InterruptedException. I can call Thread.currentThread.interrupt () and then throw the exception to calling class or i can directly throw it to calling class or is there any better way to handle it ?

Answer

Nathan Hughes picture Nathan Hughes · Mar 1, 2016

If you have a dedicated thread that is looping and polling, that sounds to me like something that needs to be terminated when the program ends; unless it is a daemon thread (implying you are happy with it going away with no chance to cleanup or close resources) it needs to be able to handle interruption. Using WatchService seems like a good idea, but the code that uses the WatchService still has to know how to handle interruption.

If you are writing a Runnable or Callable that sleeps, you can use the InterruptedException to exit whatever looping you're doing, or you can catch the exception and restore the interrupt flag so that the next check of the interrupt flag (using Thread.currentThread().isInterrupted()) can see that the thread has been interrupted:

while(!Thread.currentThread().isInterrupted()){  
   //do something   
   try{  
     Thread.sleep(5000);    
   } catch(InterruptedException e){  
        Thread.currentThread().interrupt();
   }
}

Alternatively you can use the InterruptedException to get out of the loop:

try {
    while (!Thread.currentThread().isInterrupted()) {
        // do something
        Thread.sleep(5000);
    }
} catch (InterruptedException e) {
    // flag value is not used here
    Thread.currentThread().interrupt(); 
}

If you are developing an object that you expect to nest inside other objects, then throw the exception and add it to the method signature. As an example look at the API doc for classes in the java.util.concurrent packages, like BlockingQueue, see how methods like put and offer throw InterruptedException. When objects made for concurrency are composed together they need to cooperate (and make sure they don't lose track of interrupted status) in order to make sure that they can clean up and terminate in a responsive manner.