-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBuffer.java
48 lines (44 loc) · 1.07 KB
/
Buffer.java
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
/**
* PS Software Engineering WS2015 <br>
* <br>
*
* Buffer Class to save instances of an object for further processing by a
* Consumer
*
* @author Kevin Schoergnhofer, Markus Seiwald
*
*/
public class Buffer<T extends Comparable<T>> {
private T[] items;
private int producerCounter = 0;
private int consumerCounter = 0;
/**
* default constructor
* @param size sets the maximum number of items the Buffer can save at once
*/
public Buffer(int size) {
this.items = (T[]) new Comparable[size];
}
protected synchronized void put(T item) throws InterruptedException {
while (items[producerCounter] != null) {
wait();
}
items[producerCounter] = item;
producerCounter++;
if (producerCounter == items.length)
producerCounter = 0;
notifyAll();
}
protected synchronized T take() throws InterruptedException {
while (items[consumerCounter] == null) {
wait();
}
T item = items[consumerCounter];
items[consumerCounter] = null;
consumerCounter++;
if (consumerCounter == items.length)
consumerCounter = 0;
notifyAll();
return item;
}
}