-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMessageQueue.java
More file actions
59 lines (41 loc) · 1.15 KB
/
MessageQueue.java
File metadata and controls
59 lines (41 loc) · 1.15 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
package com.codecafe.concurrency.threadsignalling;
import java.util.ArrayList;
import java.util.List;
class MessageQueue {
List<String> messages;
int limit;
// buffer is bounded
public MessageQueue(int limit) {
messages = new ArrayList<>();
this.limit = limit;
}
public boolean isFull() {
return messages.size() == limit;
}
public boolean isEmpty() {
return messages.size() == 0;
}
public synchronized void enqueue(String message) throws InterruptedException {
// releases the lock on the queue object and waits for the notification
while (isFull()) {
this.wait();
}
messages.add(message);
// once producer sends the message, notify the consumer to consume the message
this.notify();
// and sleep
Thread.sleep(100);
}
public synchronized String dequeue() throws InterruptedException {
while (isEmpty()) {
// wait till producer sends a message
this.wait();
}
String message = messages.remove(0);
// after consuming the message, signal the producer to send more messages
this.notify();
// and sleep
Thread.sleep(1000);
return message;
}
}