What is the good practice of checking for InterruptedException?

I'm new to the Java world, so bear with me if this is a stupid question.

I recently saw this code in the run () method of a Runnable.

try { if (Thread.interrupted()) { throw new InterruptedException(); } // do something if (Thread.interrupted()) { throw new InterruptedException(); } // do something if (Thread.interrupted()) { throw new InterruptedException(); } // and so on } catch (InterruptedException e){ // Handle exception } finally { // release resource } 

How often and where should you check for thread interruption, which is good practice for it?

+4
source share
3 answers

it's usually not what you just sprinkle with your code. however, if you expect to be able to cancel the asynchronous task, a periodic interrupt check may be required. in other words, this is usually what you would add after the fact when you define a body of code that should be more susceptible to interruption.

+5
source

Usually I don’t see a mechanism for interrupting a stream - similarly, if your code does not interrupt streams, then the streams do not need to check if they were interrupted. If, however, your program uses a thread interrupt mechanism, then a good place to check if (Thread.interrupted ()) is in the top-level loop in your Runnable: Runnable will often look like

 run() { while(true) { ... } } 

Instead, your looks like

 run() { try { while(true) { if(Thread.interrupted()) { throw new InterruptedException(); } ... } } catch (InterruptedException ex) { ... } } 
+3
source

A thread is interrupted only when someone calls the interrupt() method. If you never call interrupt() and you are not working with a library that calls interrupt() (and something you expect will be written), you do not need to check for interrupts.

The main reason someone wants to interrupt a thread is to cancel the lock or long-term task. For example, the wait() lock mechanism usually causes the thread to wait forever for notification, but another thread may interrupt to stop the wait thread (otherwise this would cancel the operation).

+2
source

All Articles