开发者

Managing InterruptedException

开发者 https://www.devze.com 2023-03-27 12:25 出处:网络
I have read http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html I decide to make my lock uncancelable task by

I have read http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html

I decide to make my lock uncancelable task by

try {
    lockedRecords.wait();
} catch (Interru开发者_运维百科ptedException e) {
    interrupted = true;
}

but is there a need to

} finally {
    if (interrupted) {
        Thread.currentThread().interrupt();
    }
}

The article says that you should call interrupt() to preserve the interrupted status. I'm still very blur, so what if I set .interrupt? what happens next? a bit lost on this.. any input?

What value does it bring to my program? Please kindly explain in layman terms, greatly appreciated :D


What's important here is the code that is not written in the example. The method in the example (getNextTask) could be used in:

while (!Thread.interrupted()) {
   Task task = getNextTask(queue);  
   doSomething(task);
}
System.out.println("The thread was interrupted while processing tasks.");
System.out.println("...stopped processing.");

The while loop above executes forever, unless someone interrupts the thread on which this loop runs.

If the interrupt status is not reset as is done in getNextTask however, when someone tries to interrupt the thread when the thread is in queue.take in getNextTask, then the interrupt is lost and the bit of code I wrote above will never stop looping.

The whole point of the example on the IBM webpage is that you must be very careful when you swallow an interrupt since it might accidentally make a thread impossible to interrupt.


Just swallowing the InterruptedException is fine as long as you know that the current thread will terminate after your task is done and returns.

Problems may arise when using some thread pool, like ExecutorService, where usually the threads continue to run after a task has completed, waiting for the next task to come. In this case the pooled thread should be notified it was interrupted so that it can do whatever is appropriate in this situation, e.g. perform a clean shutdown and exit.

Thus, it is good practice and more safe to make sure you restore the interrupted state before returning from your routine.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号