-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBoundedBuffer.java
More file actions
76 lines (63 loc) · 1.91 KB
/
BoundedBuffer.java
File metadata and controls
76 lines (63 loc) · 1.91 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
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Created by Phil on 8/21/2015.
*/
public class BoundedBuffer {
private int[] buffer;
private int insertionPoint;
private int removalPoint;
private int size;
private final Lock lock = new ReentrantLock();
private Condition notFull = lock.newCondition();
private Condition notEmpty = lock.newCondition();
private int capacity;
public BoundedBuffer(int capacity) {
this.capacity = capacity;
buffer = new int[capacity];
insertionPoint = 0;
removalPoint = 0;
}
public void deposit(int i) throws InterruptedException {
lock.lock();
try {
if(size == capacity) {
System.out.println("full! Waiting...");
notFull.await();
}
System.out.println("depositing " + i + "...");
buffer[insertionPoint] = i;
insertionPoint = (insertionPoint + 1)%capacity;
size++;
notEmpty.signal();
}
finally {
lock.unlock();
}
}
public int withdrawal() throws InterruptedException {
lock.lock();
try {
if(size == 0) {
System.out.println("empty! Waiting...");
notEmpty.await();
}
int retVal = buffer[removalPoint];
removalPoint = (removalPoint + 1)%capacity;
size--;
notFull.signal();
return retVal;
}
finally {
lock.unlock();
}
}
public static void main(String[] args) {
BoundedBuffer buffer = new BoundedBuffer(10);
Thread producer = new Thread(new Producer(buffer));
Thread consumer = new Thread(new Consumer(buffer));
producer.start();
consumer.start();
}
}