Producer-Consumer

Origin: unknown
Reason: To coordinate the asynchronous production and consumption of information.
Synopsis: Producers and consumers exchange information via a queue. The code to pull information from the queue is guarded.
Example: A trouble-ticket dispatching system receives tickets from clients. Dispatchers pull tickets and forward them to the appropriate troubleshooter.
Solution:
Producer Thic class supplies objects representing the information used by the Consumer and places them in the Queue. Production and consumption of objects are asynchronous.
Queue This class holds produced objects that cannot be consumed immediately.
Consumer This class pulls from the Queue and uses the object produced by the Producer. If the Queue is empty it waits.
See also: GuardedSuspension (it is used by this pattern)
Filter (it is a simple form of this pattern)
Scheduler (this pattern is a special case of scheduling)
Note: The coordination of producers and consumers can be managed by the queue or by the producers and consumers themselves. The following code sketches the latter.

The producer is a thread whose run methods looks like:

public void run () {
    for (;;) {
        Object object = ... // produce an object
        synchronized (queue) {
            queue.enqueue (object);
            queue.notify ();
        }
    }
}
The consumer is a thread whose run methods looks like:
public void run () {
    for (;;) {
        synchronized (queue) {
	    while (queue.isEmpty ()) { queue.wait (); }
            Object object = queue.dequeue ();
        }
        ... // consume the object
    }
}