01: /**
02: * This program implements the bounded buffer using shared memory.
03: * Note that this solutions is NOT thread-safe. It will be used
04: * to illustrate thread safety using Java synchronization in Chapter 7.
05: *
06: * Figure 4.10
07: */
08:
09: public class BoundedBuffer implements Buffer
10: {
11: private static final int BUFFER_SIZE = 3;
12:
13: /**
14: * volatile does not appear in the printed text. A discussion of
15: * volatile is in chapter 7.
16: */
17: private volatile int count; // number of items in the buffer
18:
19: private int in; // points to the next free position in the buffer
20: private int out; // points to the next full position in the buffer
21: private Object[] buffer;
22:
23: public BoundedBuffer()
24: {
25: // buffer is initially empty
26: count = 0;
27: in = 0;
28: out = 0;
29:
30: buffer = new Object[BUFFER_SIZE];
31: }
32:
33: // producer calls this method
34: public void insert(Object item) {
35: while (count == BUFFER_SIZE) ; // do nothing
36:
37: // add an item to the buffer
38: ++count;
39: buffer[in] = item;
40: in = (in + 1) % BUFFER_SIZE;
41:
42: if (count == BUFFER_SIZE)
43: System.out.println("Producer Entered " + item + " Buffer FULL");
44: else
45: System.out.println("Producer Entered " + item + " Buffer Size = " + count);
46: }
47:
48: // consumer calls this method
49: public Object remove() {
50: Object item;
51:
52: while (count == 0)
53: ; // do nothing - nothing to consume
54:
55: // remove an item from the buffer
56: --count;
57: item = buffer[out];
58: out = (out + 1) % BUFFER_SIZE;
59:
60: if (count == 0)
61: System.out.println("Consumer Consumed " + item + " Buffer EMPTY");
62: else
63: System.out.println("Consumer Consumed " + item + " Buffer Size = " + count);
64:
65: return item;
66: }
67:
68: }