Either re-interrupt this method or rethrow the "InterruptedException" that can be caught here.
2023, Jan 26
problem
- 소나큐브에 검출된 코드로 문제는 CompletsbleFuture를 통해 get으로 block 반환값을 얻는 과정에 get메소드에 throws InterruptedException을 선언하고 있던 것
public <T> T apiFutureSupplier(FeignAsyncSupplierClient feignAsyncClient, Object o, Class<T> rt) {
try {
return CompletableFuture.supplyAsync(() -> feignAsyncClient.execute(o), taskExecutor)
.thenApply(response -> JsonUtil.fromJson(response, rt)).get();
} catch (Exception e) {
throw new FeignAsyncException(e.getMessage());
}
}
sonarqube
"InterruptedException" should not be ignored
InterruptedExceptions should never be ignored in the code,
and simply logging the exception counts in this case as "ignoring".
The throwing of the InterruptedException clears the interrupted state of the
Thread, so if the exception is not handled properly the fact
that the thread was interrupted will be lost.
Instead, InterruptedExceptions should either be rethrown
- immediately or after cleaning up the method's state
- or the thread should be re-interrupted by calling Thread.interrupt()
even if this is supposed to be a single-threaded application.
Any other course of action risks delaying thread shutdown
and loses the information that the thread was interrupted
- probably without finishing its task.
Similarly, the ThreadDeath exception should also be propagated.
According to its JavaDoc:
If ThreadDeath is caught by a method,
it is important that it be rethrown so that the thread actually dies.
- sonarqube는 get이 명시적으로 throw하고 있는 InterruptedException을 잡아서 제대로 처리하는 요구이다.
- throw된 상태라면 이미 interrupt에 의해 쓰레드가 중단된 것인데, 이때는 이미 interrupted된 상태가 사라져서 다른 쓰레드에서는 이 사실을 알 수가 없다.
- 그래서 Thread.interrupt()를 호출해서 target쓰레드가 interrupt되었는지 확인하고 알려줄 필요가 있다.
- 그리고 catch해서 sout한다거나 로깅한다고 해결되지 않는다.
solution
public void run () {
try {
while (true) {
// do stuff
}
}catch (InterruptedException e) {
LOGGER.log(Level.WARN, "Interrupted!", e);
// Restore interrupted state...
Thread.currentThread().interrupt();
}
}
- interruptedException을 catch해서 다시 한번 interrupt를 걸고 해당 Thread를 종료하도록 한다.
reference
https://yeon-kr.tistory.com/199