Java Reference
In-Depth Information
Chapters 16-20. We discuss
multiple-element buffers
in Section 23.8. Because our
Block-
ingBuffer
class uses the
thread-safe
ArrayBlockingQueue
class to manage all of its shared
state (the shared buffer in this case),
BlockingBuffer
is itself
thread safe
, even though we
have not implemented the synchronization ourselves.
1
// Fig. 23.14: BlockingBuffer.java
2
// Creating a synchronized buffer using an ArrayBlockingQueue.
3
import
java.util.concurrent.ArrayBlockingQueue;
4
5
public
class
BlockingBuffer
implements
Buffer
6
{
7
private final
ArrayBlockingQueue<Integer> buffer;
// shared buffer
8
9
public
BlockingBuffer()
10
{
11
buffer =
new
ArrayBlockingQueue<Integer>(
1
);
12
}
13
14
// place value into buffer
15
public
void
blockingPut(
int
value)
throws
InterruptedException
16
{
17
buffer.put(value);
// place value in buffer
18
System.out.printf(
"%s%2d\t%s%d%n"
,
"Producer writes "
, value,
19
"Buffer cells occupied: "
, buffer.size());
20
}
21
22
// return value from buffer
23
public
int
blockingGet()
throws
InterruptedException
24
{
25
int
readValue = buffer.take();
// remove value from buffer
26
System.out.printf(
"%s %2d\t%s%d%n"
,
"Consumer reads "
,
27
readValue,
"Buffer cells occupied: "
, buffer.size());
28
29
return
readValue;
30
}
31
}
// end class BlockingBuffer
Fig. 23.14
|
Creating a synchronized buffer using an
ArrayBlockingQueue
.
BlockingBuffer
implements interface
Buffer
(Fig. 23.9) and uses classes
Producer
(Fig. 23.10 modified to remove line 28) and
Consumer
(Fig. 23.11 modified to remove
line 28) from the example in Section 23.5. This approach demonstrates encapsulated syn-
chronization—
the threads accessing the shared object are unaware that their buffer accesses are
now synchronized
. The synchronization is handled entirely in the
blockingPut
and
block-
ingGet
methods of
BlockingBuffer
by calling the synchronized
ArrayBlockingQueue
methods
put
and
take
, respectively. Thus, the
Producer
and
Consumer
Runnable
s are
properly synchronized simply by calling the shared object's
blockingPut
and
block-
ingGet
methods.
Line 17 in method
blockingPut
(Fig. 23.14, lines 15-20) calls the
ArrayBlocking-
Queue
object's
put
method. This method call blocks if necessary until there's room in the
buffer
to place the
value
. Method
blockingGet
(lines 23-30) calls the
ArrayBlocking-