Bird
0
0

What will happen when the following Java Kafka Producer code is executed?

medium📝 Predict Output Q4 of 15
Kafka - Producers
What will happen when the following Java Kafka Producer code is executed?
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
KafkaProducer producer = new KafkaProducer<>(props);
ProducerRecord record = new ProducerRecord<>("my-topic", "key1", "value1");
producer.send(record);
producer.close();
AThe message will not be sent because the topic 'my-topic' does not exist.
BThe code will throw a serialization error due to missing serializers.
CThe message will be sent but the producer will remain open causing resource leaks.
DThe message with key 'key1' and value 'value1' is sent to 'my-topic' and producer is closed properly.
Step-by-Step Solution
Solution:
  1. Step 1: Check configuration

    The properties specify bootstrap servers and correct serializers for key and value.
  2. Step 2: Analyze code flow

    A ProducerRecord is created with key and value, then sent asynchronously using send(), and finally the producer is closed.
  3. Step 3: Consider Kafka behavior

    If the topic exists or auto-creation is enabled, the message will be sent successfully.
  4. Final Answer:

    The message with key 'key1' and value 'value1' is sent to 'my-topic' and producer is closed properly. -> Option D
  5. Quick Check:

    Proper serializers and close() used [OK]
Quick Trick: Always close producer after sending messages [OK]
Common Mistakes:
  • Assuming missing serializers cause errors when they are provided
  • Forgetting to close the producer leading to resource leaks
  • Assuming topic must exist beforehand without auto-creation

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kafka Quizzes