diff --git a/spring-kafka/src/main/java/org/springframework/kafka/core/KafkaTemplate.java b/spring-kafka/src/main/java/org/springframework/kafka/core/KafkaTemplate.java index 88ae7a46b3..19ada3f72c 100644 --- a/spring-kafka/src/main/java/org/springframework/kafka/core/KafkaTemplate.java +++ b/spring-kafka/src/main/java/org/springframework/kafka/core/KafkaTemplate.java @@ -28,6 +28,8 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; import java.util.function.Function; import org.apache.commons.logging.LogFactory; @@ -117,6 +119,8 @@ public class KafkaTemplate implements KafkaOperations, ApplicationCo private final Map micrometerTags = new HashMap<>(); + private final Lock clusterIdLock = new ReentrantLock(); + private String beanName = "kafkaTemplate"; private ApplicationContext applicationContext; @@ -500,7 +504,15 @@ else if (this.micrometerEnabled) { @Nullable private String clusterId() { if (this.kafkaAdmin != null && this.clusterId == null) { - this.clusterId = this.kafkaAdmin.clusterId(); + this.clusterIdLock.lock(); + try { + if (this.clusterId == null) { + this.clusterId = this.kafkaAdmin.clusterId(); + } + } + finally { + this.clusterIdLock.unlock(); + } } return this.clusterId; }