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,
- This is my complete program, and nowhere am interrupting the task-thread which processes the actual GET request's response. But Interruption can happen due to various factors which I understand. But my requirement is very simple to always return back some default response no matter what exception I get, even if it is
InterruptedException
. So, even without restoring the flag, my intention/requirement gets fulfilled i.e to complete theCompletableFuture
with some default response. - And nowhere in my code I am going check for
Thread.interrupted()
ORThread.currentThread().isInterrupted()
because I don't want to handle this as my requirement already got fulfilled by returning back default response. - After capturing the InterruptedException and completing the Future with some default response, am not processing anything further within this thread(Runnable).
- After executing the InterruptedException catch block, next my Main Thread will start executing with the received default response. And my Main Thread OR Parent Thread doesn't want to know OR doesn't care about if InterruptedException ever occurred-or-not. All it cares about is some valid 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 :)