Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need to handle an exception for Thread.sleep()?

To get this code to compile, I can either:

  • Put my call to Thread.sleep() in a try/catch block, or
  • Have printAll() declare that it can throw an InterruptedException.

Why do I have to do this?

class Test {
    public static void main( String[] args ) {
          printAll( args );
    }

    public static void printAll( String[] line ) {
        System.out.println( lines[ i ] );
        Thread.currentThread().sleep( 1000 ):
    }
}

(Sample code from Kathy Sierra's SCJP book.)

I know that the exception which Thread.sleep() throws is a checked exception, so I have to handle it, but in what situation does Thread.sleep() need to throw this exception?

like image 389
Neelabh Singh Avatar asked Nov 02 '14 19:11

Neelabh Singh


People also ask

Why does thread sleep need try catch?

However, it is there to make sure that there is handling code for when a thread that is sleeping, waiting or is otherwise in a "zombie"-state has interrupt-flag set and thus is interrupted, either by code or by OS-level call. So it IS in fact needed to catch, and it has valid uses.

What is the purpose of thread exception?

Exceptions are the events that occur due to the programmer error or machine error which causes a disturbance in the normal flow of execution of the program. When a method encounters an abnormal condition that it can not handle, an exception is thrown as an exception statement.

What does sleep () do in thread Java?

Thread. sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system.

What happens if there is exception in thread?

An uncaught exception will cause the thread to exit. When it bubbles to the top of Thread. run() it will be handled by the Thread's UncaughtExceptionHandler. By default, this will merely print the stack trace to the console.


2 Answers

If a method is declared in a way that it can throw checked exceptions (Exceptions that are not subclasses of RuntimeException), the code that calls it must call it in a try-catch block or the caller method must declare to throw it.

Thread.sleep() is declared like this:

public static void sleep(long millis) throws InterruptedException; 

It may throw InterruptedException which directly extends java.lang.Exception so you have to catch it or declare to throw it.

And why is Thread.sleep() declared this way? Because if a Thread is sleeping, the thread may be interrupted e.g. with Thread.interrupt() by another thread in which case the sleeping thread (the sleep() method) will throw an instance of this InterruptedException.

Example:

Thread t = new Thread() {     @Override     public void run() {         try {             System.out.println("Sleeping...");             Thread.sleep(10000);             System.out.println("Done sleeping, no interrupt.");         } catch (InterruptedException e) {             System.out.println("I was interrupted!");             e.printStackTrace();         }     } }; t.start();     // Start another thread: t t.interrupt(); // Main thread interrupts t, so the Thread.sleep() call                // inside t's run() method will throw an InterruptedException! 

Output:

Sleeping... I was interrupted! java.lang.InterruptedException: sleep interrupted     at java.lang.Thread.sleep(Native Method)     at Main$1.run(Main.java:13) 
like image 125
icza Avatar answered Oct 02 '22 16:10

icza


One Thread can communicate with and interact with another Thread, and one way that it can do it is by interrupting it: if t is another Thread, you can call t.interrupt() to ask it politely to stop what it's currently doing. This is in particular something you might want to do if t is sleeping: you might want to wake it up. What it does is to cause an InterruptedException in t's Thread.sleep() method, so that it can catch it and respond. Because of this, any time you use Thread.sleep() to make the current thread go to sleep, you have to deal with the possibility of an InterruptedException in case another thread decides to wake it up.

In your case, you've only got one Thread, so you know that there can't be an InterruptedException from elsewhere in your code. But it's a not uncommon thing to want to do in multi-threaded code.

like image 29
chiastic-security Avatar answered Oct 02 '22 17:10

chiastic-security