-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBoundedBuffer.java
More file actions
71 lines (56 loc) · 1.66 KB
/
Copy pathBoundedBuffer.java
File metadata and controls
71 lines (56 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
* BoundedBuffer.java
*
* This program implements the bounded buffer using shared memory.
* Note that this solution is NOT thread-safe. It will be used
* to illustrate thread safety using Java synchronization in Chapter 7.
*
* @author Greg Gagne, Peter Galvin, Avi Silberschatz
* @version 1.0 - July 15, 1999
* Copyright 2000 by Greg Gagne, Peter Galvin, Avi Silberschatz
* Applied Operating Systems Concepts - John Wiley and Sons, Inc.
*/
import java.util.*;
public class BoundedBuffer
{
public BoundedBuffer()
{
// buffer is initially empty
count = 0;
in = 0;
out = 0;
buffer = new Object[BUFFER_SIZE];
}
// producer calls this method
public void enter(Object item) {
while (count == BUFFER_SIZE)
; // do nothing
// add an item to the buffer
++count;
buffer[in] = item;
in = (in + 1) % BUFFER_SIZE;
if (count == BUFFER_SIZE)
System.out.println(" Buffer FULL");
}
// consumer calls this method
public Object remove() {
Object item;
while (count == 0)
; // do nothing
// remove an item from the buffer
--count;
item = buffer[out];
out = (out + 1) % BUFFER_SIZE;
if (count == 0) {
System.out.println(" Buffer EMPTY");
}
return item;
}
public static final int NAP_TIME_PRODUCER = 5;
public static final int NAP_TIME_CONSUMER = 3;
private static final int BUFFER_SIZE = 5;
private volatile int count;
private int in; // points to the next free position in the buffer
private int out; // points to the next full position in the buffer
private Object[] buffer;
}