-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMessageQueue.java
More file actions
33 lines (26 loc) · 980 Bytes
/
MessageQueue.java
File metadata and controls
33 lines (26 loc) · 980 Bytes
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
// We use https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html
import java.util.concurrent.*;
public class MessageQueue {
// We choose the LinkedBlockingQueue implementation of BlockingQueue:
private BlockingQueue<Message> queue = new LinkedBlockingQueue<Message>();
// Inserts the specified message into this queue.
public void offer(Message m) {
queue.offer(m);
}
// Retrieves and removes the head of this queue, waiting if
// necessary until an element becomes available.
public Message take() {
while (true) {
try {
return(queue.take());
}
catch (InterruptedException e) {
// This can in principle be triggered by queue.take().
// But this would only happen if we had interrupt() in our code,
// which we don't.
// In any case, if it could happen, we should do nothing here
// and try again until we succeed without interruption.
}
}
}
}