How to handle InterruptException on Future#get()?

786 Views Asked by At
public void produceMessage(String dataPushNotif) {
    PushNotif msg = PushNotif.newBuilder()
            .setDatapushnotif(dataPushNotif)
            .build();

    ListenableFuture<SendResult<String, PushNotif>> future =
            kafkaTemplate.send(destTopic, msg);

    try {
        var result = future.get(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
        log.debug(buildSuccesLogMessage(result));
    }
    catch (InterruptedException | ExecutionException | TimeoutException e) {
        log.debug("FAILED: {}", e);
    }
}

With the code above I'm getting a sonarlint warning of Either re-interrupt this method or rethrow the "InterruptedException" that can be caught here. (java:S2142)

I could handle success and failure to send gracefully with addCallback(), but I don't see any other way to set a timeout on the thread execution.

Is there any way to handle the sonarlint warning? Or handle the future gracefully with a timeout option?

1

There are 1 best solutions below

5
Gary Russell On

Don't use multi-catch and call Thread.currentThread().interrupt() in the InterruptedException catch block so that the next interruptible operation will get the exception.

It is bad practice to "swallow" interrupts.