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?
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.
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) {
...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With