CCDAK · Question #57
How can you gracefully make a Kafka consumer to stop immediately polling data from Kafka and gracefully shut down a consumer application?
The correct answer is A. Call consumer.wakeUp() and catch a WakeUpException. Calling consumer.wakeup() is the only thread-safe method on a Kafka consumer, designed specifically to interrupt a blocking consumer.poll() call from another thread - it causes the poll to throw a WakeupException, which you catch to exit the poll loop cleanly and then call…
Question
How can you gracefully make a Kafka consumer to stop immediately polling data from Kafka and gracefully shut down a consumer application?
Options
- ACall consumer.wakeUp() and catch a WakeUpException
- BCall consumer.poll() in another thread
- CKill the consumer thread
How the community answered
(24 responses)- A88% (21)
- B4% (1)
- C8% (2)
Explanation
Calling consumer.wakeup() is the only thread-safe method on a Kafka consumer, designed specifically to interrupt a blocking consumer.poll() call from another thread - it causes the poll to throw a WakeupException, which you catch to exit the poll loop cleanly and then call consumer.close() before the application exits.
Option B is wrong because consumer.poll() is not thread-safe; the Kafka consumer is single-threaded by design, so calling it from another thread causes unpredictable behavior. Option C is wrong because killing the thread abruptly prevents proper cleanup - the consumer won't commit offsets, close connections, or notify the broker, which can cause rebalance delays and duplicate message processing in other consumers.
Memory tip: Think of wakeup() as a "polite alarm clock" - it interrupts the sleeping poll and gives the consumer time to brush its teeth (commit offsets, close gracefully) before leaving the house.
Topics
Community Discussion
No community discussion yet for this question.