1
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?

BlueRey
  • 35
  • 1
  • 6
  • The sonar warning will vanish, as soon you `Thread.interrupt()`/`throw [new] InterruptedException` within (probably better? "single catch") block – xerx593 Oct 25 '22 at 10:57

1 Answers1

1

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.

Gary Russell
  • 166,535
  • 14
  • 146
  • 179
  • If I'm not mistaken `Thread.currentThread().interrupt()` will terminate the current thread, i.e the thread that's currently consuming the message? It won't cause the app to stop or any other thread to stop right? – BlueRey Oct 30 '22 at 16:45
  • You are mistaken, it simply sets the interrupted flag so that the next time the thread performs an interruptible operation it will get an immediate interrupt. If you swallow the interrupt without re-interrupting, you could cause the thread to hand for a very long time (if such an interruptible operation is performed downstream). – Gary Russell Oct 31 '22 at 12:51
  • So it won't kill the actual program or interfere with other threads that might be handling other request right? Because that's my actual concern that it would interrupt other threads – BlueRey Nov 01 '22 at 15:41
  • No; it wont affect other threads; generally, however, a thread is not usually interrupted at all; most commonly, it is when the thread is from a task executor and the executor is forced shutdown (e.g. during application shutdown). A normal executor shutdown waits for its threads to terminate. – Gary Russell Nov 01 '22 at 16:22
  • Lots of good info here: https://stackoverflow.com/questions/3976344/handling-interruptedexception-in-java – Suketu Bhuta Jan 27 '23 at 05:05