Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 769
IS_EV Avatar asked Feb 08 '17 05:02

IS_EV


Video Answer


1 Answers

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.

like image 68
Behrang Avatar answered Sep 28 '22 03:09

Behrang