Wk6L1 - Producer-Consumer Flashcards
What is the Producer-Consumer Problem?
It is a classic synchronization problem where one or more producer threads generate items to add to a shared data structure, and one or more consumer threads remove and process those items.
What is the Separation of Concerns in the Producer-Consumer Problem?
Producer: Creates tasks (e.g., adding items to a queue).
Consumer: Processes tasks (e.g., removing items from the queue).
Why is synchronization necessary for the shared queue in the Producer-Consumer Problem?
Synchronization ensures only one thread can add or remove items at a time, preventing issues like adding to a full queue or removing from an empty queue.
What is a Blocking Queue in Java?
A blocking queue is a thread-safe data structure that handles producer-consumer operations by blocking threads when the queue is full (producers) or empty (consumers).
What is the difference between Bounded and Unbounded Blocking Queues?
Bounded: Has a fixed size, implemented with arrays; producers must wait if it’s full.
Unbounded: Has no fixed size, implemented with linked lists; risk of data loss if producers can’t be blocked.
How do you determine the number of Producer and Consumer Threads?
Ideally, the average production rate should be less than or equal to the average consumption rate to prevent overloading the queue.
How do you handle shutting down a Producer-Consumer setup?
Since blocking queues don’t have a shutdown feature, you can use End of Stream or Poison Objects as markers to signal consumers to stop.
What is a Poison Object?
A special item added to the queue by producers to indicate no more items are coming. Each consumer checks for this object and terminates when it’s found.