7

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.

IS_EV
  • 988
  • 2
  • 15
  • 29

2 Answers2

6

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.

Behrang
  • 46,888
  • 25
  • 118
  • 160
  • 1
    Could not agree more. Open source has a lot of good libraries to offer, but when it comes to documentation or annotation in the source code, usually none or very brief. JDK is by far the most well documented Java source code I have ever seen. – Kevin Wang Dec 29 '17 at 23:20
  • KafkaTemplate thread-safety may depend on ProducerFactory implementation used. – Anton Yuriev Jul 25 '20 at 14:35
0

KafkaTemplate is exactly thread-safe when used with DefaultKafkaProducerFactory (see KafkaTemplate doc).

KafkaProducer itself is thread-safe (see KafkaProducer doc).

Anton Yuriev
  • 580
  • 8
  • 10