2

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 ?

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
Element
  • 25
  • 1
  • 1
  • 7
  • 3
    Are you sure you need a `Thread.sleep`? 99% of the times you don't need it and shouldn't use it. – Neijwiert Mar 01 '16 at 12:39
  • I m polling messages from a file and i have to wait 10 sec before every iteration, so i m using sleep(). Can u suggest me any better way – Element Mar 01 '16 at 12:41
  • How is the information written to the file? Do you have any control over it? – Neijwiert Mar 01 '16 at 12:43
  • No, i m only connected to file path to fetch the data. – Element Mar 01 '16 at 12:51
  • 2
    You are probably better off using a `Timer` or `ScheduledExecutorService` than putting the thread to sleep – bradimus Mar 01 '16 at 12:53
  • Does the writing process lock the file, or does it allow shared reading/writing? – Neijwiert Mar 01 '16 at 12:54
  • @neijwiert reading and writing is allowed – Element Mar 01 '16 at 13:03
  • Checkout [rxjava-file](https://github.com/davidmoten/rxjava-file), like mentioned here http://stackoverflow.com/a/31202832/2160152 – cheffe Mar 01 '16 at 14:19
  • @MohitChandak - Did you consider using java.nio.file package which provides a file change notification API, called Watch Service. This API enables you 2 register a directory with the watch service. When registering, you tell the service which types of events you are interested in: file creation, deletion, or modification. When the service detects an event of interest, it is forwarded to the registered process. The registered process has a thread (or a pool of threads) dedicated to watching for any events it has registered for. When an event comes in, it is handled as needed. – The Roy Mar 01 '16 at 14:20
  • @DROY This is a good alternative. But in my case more than one object are trying to modify the same file. What i want is that only one of them should be able to modify the file and others should not. So i was using thread. Even if i use the process which u r suggesting, i still have to go for handling something like interrupt – Element Mar 01 '16 at 15:19

4 Answers4

4

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.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
  • Wouldn't a `while (true)` in the alternative be clearer? – Esteve Sep 15 '20 at 17:25
  • @Esteve: in the first example the exception is caught inside the loop so it has to check the interrupted flag in order to leave the while loop. in the alternative example it doesn't matter as much. but if the flag is already set before the loop is entered, I would rather check the flag right away and not enter the sleep method. – Nathan Hughes Sep 15 '20 at 17:31
  • @NathanHughes noob question: why even use `if(!Thread.currentThread().isInterrupted())`? if re-throw the exception from the catch block it will anyhow will bubble-up to the caller? – Govinda Sakhare Dec 28 '21 at 11:45
  • @Govinda: I think the question assumes that the code is in the run method of a class that implements Runnable. Not only can we not let a run method throw a checked exception, exceptions can't be thrown from one thread to another, it is better here to handle it. It is certainly possible to have code in other places throw this, often the right thing to do then is put "throws InterruptedException" on the method and let it bubble up. – Nathan Hughes Dec 28 '21 at 13:53
  • @Govinda: hope that is clear. It occurs to me re-reading with your question in mind that maybe I should add some more explanation to this answer – Nathan Hughes Dec 28 '21 at 14:43
  • @NathanHughes yes much clear now. Totally forget `Runnable#run` doesn't allow throwing an exception. Thanks :) – Govinda Sakhare Dec 29 '21 at 04:35
1

In most normal code, you shouldn't use sleep. There is often a better way to do what you want.

I can call Thread.currentThread.interrupt ()

This is useful if you want to continue as normal, but without waiting.

and then throw the exception to calling class

OR I would throw an exception, you can wrap the exception with one of your choice.

or i can directly throw it to calling class

You might as well not catch in this case.

or is there any better way to handle it ?

It depends on why you expect the thread to be interrupted. if I don't expect an interrupt ever, I wrap it with an AssertionError

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

Generally, rethrow if you can, or set the interruption flag if you cannot rethrow.

A good article on this is http://www.ibm.com/developerworks/library/j-jtp05236/

from which this is the most relevant excerpt would be:

When a blocking method detects interruption and throws InterruptedException, it clears the interrupted status. If you catch InterruptedException but cannot rethrow it, you should preserve evidence that the interruption occurred so that code higher up on the call stack can learn of the interruption and respond to it if it wants to.

metlos
  • 306
  • 2
  • 5
0

I am using Thread.sleep(10000); hence i need to handle InterruptedException.

Not necessarily. There are smart ways to handle InterruptedException, and there are stupid ways. If your thread will never actually be interrupted, then does it really matter which way you pick?

Of course, if you think that your code might ever be re-used, or if you think that other programmers are going to read it, then you might want to go with the smart way. If you want to practice good coding habits, you might want to go with the smart way (lots of examples out there, just waiting to be found with a google search).

But sometimes we just want to write a quick hack, that we're going to use once and then throw away...

Solomon Slow
  • 25,130
  • 5
  • 37
  • 57