-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEnqueueMethods.java
More file actions
40 lines (32 loc) · 1.14 KB
/
EnqueueMethods.java
File metadata and controls
40 lines (32 loc) · 1.14 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
package com.codecafe.concurrency.blockingqueue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
public class EnqueueMethods {
public static void main(String[] args) {
BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(3);
// put() will block until there is no space
// inside the BlockingQueue for the element
try {
blockingQueue.put("1");
} catch (InterruptedException e) {
e.printStackTrace();
}
// add() will throw IllegalStateException if
// no space is available in the BlockingQueue
try {
blockingQueue.add("2");
} catch (IllegalStateException e) {
// no space inside BlockingQueue
}
// offer() returns false if no space
boolean wasEnqueued = blockingQueue.offer("3");
// offer(o, time, TimeUnit) blocks for the given time if no space
// then returns false if still no space is available
try {
boolean wasEnqueued2 = blockingQueue.offer("4", 1000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
// no space inside BlockingQueue
}
}
}