Java Reference
In-Depth Information
Producer writes 9 9 true
Consumer reads 9 9 false
Consumer tries to read.
Buffer empty. Consumer waits.
9 false
Producer writes 10 10 true
Consumer reads 10 10 false
Producer done producing
Terminating Producer
Consumer read values totaling 55
Terminating Consumer
Fig. 23.17
|
Two threads correctly manipulating a synchronized buffer. (Part 3 of 3.)
Study the outputs in Fig. 23.17. Observe that
every integer produced is consumed exactly
once—no values are lost, and no values are consumed more than once
. The synchronization
ensures that the
Producer
produces a value only when the buffer is
empty
and the
Con-
sumer
consumes only when the buffer is
full
. The
Producer
always goes first, the
Consumer
waits
if the
Producer
has not produced since the
Consumer
last consumed, and the
Pro-
ducer
waits if the
Consumer
has not yet consumed the value that the
Producer
most
recently produced. Execute this program several times to confirm that every integer pro-
duced is consumed exactly
once
. In the sample output, note the highlighted lines indi-
cating when the
Producer
and
Consumer
must
wait
to perform their respective tasks.
Bounded Buffers
The program in Section 23.7 uses thread synchronization to guarantee that two threads
manipulate data in a shared buffer correctly. However, the application may not perform
optimally. If the two threads operate at different speeds, one of them will spend more (or
most) of its time waiting. For example, in the program in Section 23.7 we shared a single
integer variable between the two threads. If the
Producer
thread produces values
faster
than the
Consumer
can consume them, then the
Producer
thread
waits
for the
Consumer
,
because there are no other locations in the buffer in which to place the next value. Simi-
larly, if the
Consumer
consumes values
faster
than the
Producer
produces them, the
Con-
sumer
waits
until the
Producer
places the next value in the shared buffer. Even when we
have threads that operate at the
same
relative speeds, those threads may occasionally be-
come “out of sync” over a period of time, causing one of them to
wait
for the other.
Performance Tip 23.3
We cannot make assumptions about the relative speeds of concurrent threads
—
interactions that occur with the operating system, the network, the user and other compo-
nents can cause the threads to operate at different and ever-changing speeds. When this
happens, threads wait. When threads wait excessively, programs become less efficient,
interactive programs become less responsive and applications suffer longer delays.