-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPeekMethods.java
More file actions
28 lines (20 loc) · 802 Bytes
/
PeekMethods.java
File metadata and controls
28 lines (20 loc) · 802 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
package com.codecafe.concurrency.blockingqueue;
import java.util.NoSuchElementException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
// both peek() and element() methods allow to get the
// first element of the queue without removing it
// the difference between peek() and element() is that
// if the queue is empty then peek() will return null
// but element() will throw a NoSuchElementException
public class PeekMethods {
public static void main(String[] args) {
BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(3);
String element1 = blockingQueue.peek();
try {
String element2 = blockingQueue.element();
} catch (NoSuchElementException e) {
System.out.println("BlockingQueue is empty");
}
}
}