Search code examples
spring-bootapache-kafkakafka-producer-api

Is KafkaTemplate thread safe


Is KafkaTemplate in spring boot thread safe. Can I create one KafkaTemplate and use it for sending information to the same kafka topic for multiple requests in my web service.


Solution

  • Yes, KafkaTemplate is designed to be thread-safe. If you look at its source code, you see the following member variable declarations:

    protected final Log logger = LogFactory.getLog(this.getClass()); //NOSONAR
    
    private final ProducerFactory<K, V> producerFactory;
    
    private final boolean autoFlush;
    
    private final boolean transactional;
    
    private final ThreadLocal<Producer<K, V>> producers = new ThreadLocal<>();
    
    private RecordMessageConverter messageConverter = new MessagingMessageConverter();
    
    private volatile String defaultTopic;
    

    Judging by the ThreadLocal and volatile variable definitions, you can infer that it is designed to be used from multiple threads, hence it must be thread-safe (if it is not, then you should submit a bug report).

    It would be nicer if the designers had annotated it with an informational @ThreadSafe though or had at least pointed this out in the class's JavaDoc comments.