From 5dffa839814654ac643d9cd489cd6451a406132b Mon Sep 17 00:00:00 2001 From: Gary Russell Date: Wed, 3 Mar 2021 11:19:37 -0500 Subject: [PATCH] GH-1727: Close Producer if initTransactions Fails Resolves https://github.com/spring-projects/spring-kafka/issues/1727 --- .../kafka/core/DefaultKafkaProducerFactory.java | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/spring-kafka/src/main/java/org/springframework/kafka/core/DefaultKafkaProducerFactory.java b/spring-kafka/src/main/java/org/springframework/kafka/core/DefaultKafkaProducerFactory.java index 0b8f1d99..351d026f 100644 --- a/spring-kafka/src/main/java/org/springframework/kafka/core/DefaultKafkaProducerFactory.java +++ b/spring-kafka/src/main/java/org/springframework/kafka/core/DefaultKafkaProducerFactory.java @@ -58,6 +58,7 @@ import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextStoppedEvent; import org.springframework.core.log.LogAccessor; +import org.springframework.kafka.KafkaException; import org.springframework.kafka.support.TransactionSupport; import org.springframework.lang.Nullable; import org.springframework.util.Assert; @@ -716,7 +717,20 @@ public class DefaultKafkaProducerFactory extends KafkaResourceFactory } checkBootstrap(newProducerConfigs); newProducer = createRawProducer(newProducerConfigs); - newProducer.initTransactions(); + try { + newProducer.initTransactions(); + } + catch (RuntimeException ex) { + try { + newProducer.close(this.physicalCloseTimeout); + } + catch (RuntimeException ex2) { + KafkaException newEx = new KafkaException("initTransactions() failed and then close() failed", ex); + newEx.addSuppressed(ex2); + throw newEx; // NOSONAR - lost stack trace + } + throw new KafkaException("initTransactions() failed", ex); + } CloseSafeProducer closeSafeProducer = new CloseSafeProducer<>(newProducer, remover, prefix, this.physicalCloseTimeout, this.beanName, this.epoch.get());