Good Day!
I have been going through the Java Docs & some online resources on properly handling the InterruptedException
due to bug reported by SonarQube. But not sure if I 100% understood if Interruption flag
status always has to be restored whenever InterruptedException occurs inside a place where we can't throw exception for Ex: Runnable implementation.
Lets consider below replicated demo example code, where the main method is responsible for initiating some async method.The async method makes the Http GET request and processes(by taking runnable
as argument to the addListener method) the response asynchronously.
Note : Now my query is Do I have to restore Interruption status
flag at line#35. Why asking this is because,
InterruptedException
. So, even without restoring the flag, my intention/requirement gets fulfilled i.e to complete the CompletableFuture
with some default response.Thread.interrupted()
OR Thread.currentThread().isInterrupted()
because I don't want to handle this as my requirement already got fulfilled by returning back default response.Incase if I still want to restore the Interruption flag status, could someone please explain why to restore the same, and how can my code go wrong if I don't restore it?
. Because, as I said in above 4 points my requirement gets fulfilled even without restoring the flag.
Any enlightment/clarification on this topic for the above exact scenario is highly appreciatable.
Thanks in Advance :)
In your program there you probably don't need to handle InterruptedException
indeed.
But in a general case swallowing InterruptedException
is a bad idea.
The main reason is that Thread.interrupt()
(which causes InterruptedException
) is the only way to interrupt many blocking operations provided by Java's standard library.
For instance, the proper handling of InterruptedException
is typically required when we want to gracefully shutdown our application (i.e. when we want to close files, network connections and other resources before shutdown).
Some information about this can be found in Thread.interrupt()
javadocs.
Also I would recommend this SO answer and related chapters in "Java Concurrency In Practice", mentioned there.