IS_EV
IS_EV

Reputation: 1048

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.

Upvotes: 8

Views: 3646

Answers (2)

Anton Yuriev
Anton Yuriev

Reputation: 628

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

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

Upvotes: 0

Behrang Saeedzadeh
Behrang Saeedzadeh

Reputation: 47961

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.

Upvotes: 7

Related Questions