InterruptedException

InterruptedException

Certain methods cannot be executed by the JVM alone. JVM takes the help of the underlying operating system to do the job. Such methods are known as native methods. For example, for all the file operations and thread operations, the JVM should communicate with the operating system and with the operating system cooperation, the task intended will be achieved. File management and thread management etc. are managed entirely by the OS. Any language should communicate and take the help of OS.

Any problem in the communication (known as communication gap) and any programmer's task is not done successfully, the JVM informs through an exception and especially as a checked exception. The name of the checked exception is included in the method signature or constructor signature. Some checked exceptions with constructor signatures are given hereunder.

One example of checked exception is InterruptedException very often used in thread operations. Many thread methods throw InterruptedException. Observe the following two method signatures of Thread class.

Both the methods sleep() and join() throw a checked exception – InterruptedException. While using these methods, these methods must be placed in try-catch blocks; else program does not compile.

The following program uses these two methods and handles InterruptedException.

The program is given to stress more on InterruptedException. Coding explanation (extending Thread, run() and sleep()) of the above program is available at "Creating and Spawning Threads".

The above main() method can be modified to throw the InterruptedException instead of handling it in try-catch block. Using throws, instead of handling with try-catch block, is not a robust way of programming and can be used in sample code development.

Why the methods sleep(long milliseconds) and join() throw InterruptedException?

The sleep() method inactivates the smooth running thread for the time passed as parameter in milliseconds. The communication goes from Java to OS to inactivate. Due to the complex algorithm of Thread Scheduler, the sleep time may not have been affected exactly specified. Say, 1000 milliseconds may be affected as 999 or 1001 milliseconds. If it is done like this, the programmer output may differ. Then it is programmers job to take care of this situation (which may be very very rare). He can take some alternative action to rectify the problem in the catch block.

Similarly, join() method communicates with the parent thread. The JVM does not allow the parent thread to die before the child dies. If the child thread dies before the parent, the child becomes orphan thread and the program may give different outputs when executed each time. This problem is indicated by the designers with InterruptedException.

Leave a Reply

Your email address will not be published. Required fields are marked *