You don’t need to close the producer after sending each message. You can close if when you no longer need to send any messages. By default, the producer sends messages asynchronously. So you’ll sometimes encounter delays in receiving messages. To overcome this, you can call the .get() method, something like this:

producer.send(new ProducerRecord<>(topic, payload)).get();

This will immediately send messages to the topic, synchronously. Please try this once. But because this doesn’t delegate the work to a background thread, this will be slower, as it is a blocking operation (if I’m not wrong and remember it properly). Please correct me if I’m wrong.

Coding, machine learning, reading, sleeping, listening, potato. and

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store