-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimpleObjectFIFO.java
More file actions
76 lines (59 loc) · 1.57 KB
/
Copy pathSimpleObjectFIFO.java
File metadata and controls
76 lines (59 loc) · 1.57 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
72
73
74
75
76
package threadbook.ch18;
public class SimpleObjectFIFO extends Object {
private Object[] queue;
private int capacity;
private int size;
private int head;
private int tail;
public SimpleObjectFIFO(int cap) {
capacity = ( cap > 0 ) ? cap : 1; // at least 1
queue = new Object[capacity];
head = 0;
tail = 0;
size = 0;
}
public synchronized int getSize() {
return size;
}
public synchronized boolean isFull() {
return ( size == capacity );
}
public synchronized void add(Object obj) throws InterruptedException {
while ( isFull() ) {
wait();
}
queue[head] = obj;
head = ( head + 1 ) % capacity;
size++;
notifyAll(); // let any waiting threads know about change
}
public synchronized Object remove() throws InterruptedException {
while ( size == 0 ) {
wait();
}
Object obj = queue[tail];
queue[tail] = null; // don't block GC by keeping unnecessary reference
tail = ( tail + 1 ) % capacity;
size--;
notifyAll(); // let any waiting threads know about change
return obj;
}
public synchronized void printState() {
StringBuffer sb = new StringBuffer();
sb.append("SimpleObjectFIFO:\n");
sb.append(" capacity=" + capacity + "\n");
sb.append(" size=" + size);
if ( isFull() ) {
sb.append(" - FULL");
} else if ( size == 0 ) {
sb.append(" - EMPTY");
}
sb.append("\n");
sb.append(" head=" + head + "\n");
sb.append(" tail=" + tail + "\n");
for ( int i = 0; i < queue.length; i++ ) {
sb.append(" queue[" + i + "]=" + queue[i] + "\n");
}
System.out.print(sb);
}
}