Introduction
The Java programming language supports multiple threads, using a monitor construction for synchronization. In the Java language, a method can be declared as synchronized. A built-in mechanism ensures that only one Java thread can execute an object's synchronized methods at a time. The mechanism also allows threads to wait for resources to become available, and allows a thread that makes a resource available to notify other threads that are waiting for the resource. This web page describes this mechanism and its use. But first, we need to look at an example that illustrates why synchronization is needed.
The Bounded Buffer Problem
In the Bounded Buffers problem, there are two kinds of processes or threads: producers and consumers. Producers take buffers from a queue of empty buffers, put content into the buffers, and place the buffers into a queue of full buffers. Consumers take buffers from a queue of full buffers, do something with the buffers' contents, and place the buffers back onto the queue of empty buffers. Each of the buffer queues has a bounded capacity for buffers. Processes communicating through a pipe or communicating through mailboxes are examples of the Bounded Buffers problem.
There is generally only one queue of empty buffers, maintained by the operating system. It provides all buffers for processes or threads. There can be multiple producers, consumers, and queues of full buffers. The queues of full buffers usually have a small capacity, on the order of 10 buffers. We generally only need to consider a single queue of full buffers at a time. The following picture illustrates the flow of buffers.
Figure 1. Buffer flow in the Bounded Buffers Problem.
A First Solution
When we have a good solution to the Bounded Buffers problem, the coordination between producers and consumers will be controlled by two BufferQueue objects representing the queue of empty buffers and the queue of full buffers. The following code is an implementation of a BufferQueue class that works well in a single-threaded environment.
Testing the First Solution
We are limited in the kind of testing we can do on this first version of the BufferQueue class. There is no good way of making producers wait for empty buffers or making consumers wait for full buffers. So we will only use producers. Initially the queue of empty buffers has 10 buffers and the queue of full buffers has none. We first run a single producer that moves buffers from the queue of empty buffers to the queue of full buffers as long as the queue of empty buffers is not empty. The producer kills time for 20 milliseconds on the average after removing a buffer from the queue of empty buffers and kills time for 20 milliseconds on the average after putting the buffer on the queue of full buffers
No comments:
Post a Comment