I was reading source code of Spring KafkaTemplate(org.springframework.kafka.core) and came across this piece of code:
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;
private volatile ProducerListener<K, V> producerListener = new LoggingProducerListener<K, V>();
As you see, variables like defaultTopic and producerListener are set to volatile which I presume to make them memory visible once being changed.
So I am confused why meesageConverter was not set to the same.
We generally don't expect configuration properties, such as the message converter to be changed at runtime so there is no need to make it volatile. If you have such a requirement, subclass the template and override the setter with a synchronized
method (calling super.set...()
).
You are looking at an older version of the code; those variables are no longer volatile
.