public class BlockingBuffer implements Buffer
1: // Fig. 23.15: BlockingBuffer.java
2: // Class synchronizes access to a blocking buffer.
3: import java.util.concurrent.ArrayBlockingQueue;
4:
5: public class BlockingBuffer implements Buffer
6: {
7: private ArrayBlockingQueue<Integer> buffer;
8:
9: public BlockingBuffer()
10: {
11: buffer = new ArrayBlockingQueue<Integer>( 3 );
12: } // end BlockingBuffer constructor
13:
14: // place value into buffer
15: public void set( int value )
16: {
17: try
18: {
19: buffer.put( value ); // place value in circular buffer
20: System.out.printf( "%s%2d\t%s%d\n", "Producer writes ", value,
21: "Buffers occupied: ", buffer.size() );
22: } // end try
23: catch ( Exception exception )
24: {
25: exception.printStackTrace();
26: } // end catch
27: } // end method set
28:
29: // return value from buffer
30: public int get()
31: {
32: int readValue = 0; // initialize value read from buffer
33:
34: try
35: {
36: readValue = buffer.take(); // remove value from circular buffer
37: System.out.printf( "%s %2d\t%s%d\n", "Consumer reads ", readValue,
38: "Buffers occupied: ", buffer.size() );
39: } // end try
40: catch ( Exception exception )
41: {
42: exception.printStackTrace();
43: } // end catch
44:
45: return readValue;
46: } // end method get
47: } // end class BlockingBuffer
48:
49:
50: /**************************************************************************
51: * (C) Copyright 1992-2005 by Deitel & Associates, Inc. and *
52: * Pearson Education, Inc. All Rights Reserved. *
53: * *
54: * DISCLAIMER: The authors and publisher of this book have used their *
55: * best efforts in preparing the book. These efforts include the *
56: * development, research, and testing of the theories and programs *
57: * to determine their effectiveness. The authors and publisher make *
58: * no warranty of any kind, expressed or implied, with regard to these *
59: * programs or to the documentation contained in these books. The authors *
60: * and publisher shall not be liable in any event for incidental or *
61: * consequential damages in connection with, or arising out of, the *
62: * furnishing, performance, or use of these programs. *
63: *************************************************************************/