-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathThreadSafeCircularQueue.java
More file actions
executable file
·52 lines (42 loc) · 1.02 KB
/
Copy pathThreadSafeCircularQueue.java
File metadata and controls
executable file
·52 lines (42 loc) · 1.02 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
package com.vee.algorithms.concurrency;
import com.vee.algorithms.datastructures.CircularQueue;
public class ThreadSafeCircularQueue {
private final Object lock = new Object();
private final CircularQueue queue;
private final int maxSize;
public ThreadSafeCircularQueue(int maxSize) {
this.queue = new CircularQueue(maxSize);
this.maxSize = maxSize;
}
public void enqueue(String value) {
synchronized (lock) {
while (size() == maxSize) {
waitForNotification();
}
queue.enqueue(value);
lock.notifyAll();
}
}
private synchronized void waitForNotification() {
try {
lock.wait();
} catch (InterruptedException e) {
}
}
public String dequeue() {
synchronized (lock) {
while (isEmpty()) {
waitForNotification();
}
String value = queue.dequeue();
lock.notifyAll();
return value;
}
}
public int size() {
return queue.size();
}
private boolean isEmpty() {
return queue.isEmpty();
}
}