Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a good practice of checking InterruptedException?

Tags:

java

I'm new to Java world, so bear with me if it is dumb question.

I recently saw some code like this in run() method of an Runnable object.

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 thread interruption, what is a good practice for it?

like image 583
jAckOdE Avatar asked Dec 27 '22 06:12

jAckOdE


2 Answers

it's not generally something that you just sprinkle throughout your code. however, if you are expecting to be able to cancel an asynchronous task, it may be necessary to periodically check for interruption. in other words, it's typically something you would add after the fact when you identify a body of code which needs to be more responsive to interruption.

like image 195
jtahlborn Avatar answered Jan 15 '23 15:01

jtahlborn


I usually don't see the thread interrupt mechanism being used - likewise, if your code isn't interrupting threads, then the threads don't need to check to see if they've been interrupted. If however your program is using the thread interrupt mechanism, then a good place to put the if(Thread.interrupted()) check is at the top-level loop in your Runnable: a Runnable will often look like

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

Yours would instead look like

run() {
    try {
        while(true) {
            if(Thread.interrupted()) {
                throw new InterruptedException();
            }
            ...
         }
    } catch (InterruptedException ex) {
        ...
    }
}
like image 39
Zim-Zam O'Pootertoot Avatar answered Jan 15 '23 16:01

Zim-Zam O'Pootertoot