- Objective
Write a Java thread program to illustrate Producer-Consumer problem
- Description
This problem commonly occurs in data flow decomposition in typical distributed computing. Usually, the problem can be decomposed in different
ways on target architecture of the computing system, and different tasks can do different work. The most important issue is how the data flow
between different tasks requires serious attention from performance point of view. The producer-consumer problem falls in this category
in which the program has ability to execute in parallel. In this, the output of one task, the producer, becomes the input to another,
the consumer . The two tasks are performed by different threads, and the second one, consumer , cannot start until the
producer finishes
some portion of its work. This is quite similar to the concept of pipelining in typical Parallel computing Paradigms.
The producer/consumer problem occurs in several typical scenarios. In one scenario, first task may complete many sub-tasks and decides
at some point of time, the work should be given to next task. The next task, which is executed by another thread, cannot start the work until
the previous sub-tasks are completed by first task. It is difficult to identify at what point of time the first task completes the work and the
delay caused by the first task creates a pause for the second task. After certain point of time, both the tasks can execute in parallel.
In another scenario, the first task may read of a file and the results of this become the input to next task, which might be threaded. This
process introduces substantial delay and the next step cannot begin until the first step completes the reading of file or partial reading of
the file is done. It is possible to do new piece of work in the next step and waiting for the completion of first step.
The producer-consumer problem has different benefits when decomposing a problem.
The dependence created between consumer and producer can cause significant delays if this model is implemented correctly.
There are situations
in which consumer threads are idling while waiting for producer threads. A performance sensitive design seeks to understand
the exact nature of
the dependence and diminish the delay it imposes.
In an ideal scenario, the producer and consumer plan carefully on their interaction. Also, if the consumer is finishing up while
the producer is completely done, one thread remains idle while other threads are busy working away.