diff --git a/spring-kafka/src/main/java/org/springframework/kafka/listener/KafkaMessageListenerContainer.java b/spring-kafka/src/main/java/org/springframework/kafka/listener/KafkaMessageListenerContainer.java index de258bac4..09947227b 100644 --- a/spring-kafka/src/main/java/org/springframework/kafka/listener/KafkaMessageListenerContainer.java +++ b/spring-kafka/src/main/java/org/springframework/kafka/listener/KafkaMessageListenerContainer.java @@ -2750,7 +2750,6 @@ private void pauseForNackSleep() { * @throws Error an error. */ @Nullable - @SuppressWarnings("try") private RuntimeException doInvokeRecordListener(final ConsumerRecord cRecord, // NOSONAR Iterator> iterator) { @@ -2763,7 +2762,9 @@ private RuntimeException doInvokeRecordListener(final ConsumerRecord cReco this.observationRegistry); observation.start(); - try (Observation.Scope ignored = observation.openScope()) { + Observation.Scope observationScope = observation.openScope(); + // We cannot use 'try-with-resource' because the resource is closed just before catch block + try { invokeOnMessage(cRecord); successTimer(sample, cRecord); recordInterceptAfter(cRecord, null); @@ -2802,6 +2803,7 @@ private RuntimeException doInvokeRecordListener(final ConsumerRecord cReco if (!(this.listener instanceof RecordMessagingMessageListenerAdapter)) { observation.stop(); } + observationScope.close(); } return null; } @@ -4020,6 +4022,6 @@ private static class StopAfterFenceException extends KafkaException { } - private record FailedRecordTuple(ConsumerRecord record, RuntimeException ex) { }; + private record FailedRecordTuple(ConsumerRecord record, RuntimeException ex) { } }