BlockingQueue is just like a regular Queue, except that it includes methods that will wait a specific amount of time to complete an operation.
BlockingQueue inherits all of the methods from Queue and has some extra “waiting” methods :
Method Name | Description |
offer(E e, long timeout, TimeUnit unit) | Adds item to the queue waiting the specified time, returning false if time elapses before space is available |
poll(long timeout, TimeUnit unit) | Retrieves and removes an item from the queue, waiting the specified time, returning null if the time elapses before the item is available |
A LinkedBlockingQueue, as the name implies, maintains a linked list between elements. A LinkedBlockingDeque maintains a doubly linked list between elements and implements a BlockingDeque interface. The BlockingDeque interface extends Deque much in the same way that BlockingQueue extends Queue, providing waiting methods :
Method Name | Description |
offerFirst(E e, long timeout, TimeUnit unit) | Adds an item to the front of the queue, waiting a specified time, returning false if time elapses before space is available |
offerLast(E e, long timeout, TimeUnit unit) | Adds an item to the tail of the Queue, waiting a specified time, returning false if time elapses before space is available |
pollFirst(long timeout, TimeUnit unit) | Retrieves and removes an item from the front of the queue, waiting the specified time, returning null if the time elapses before the item is available |
pollLast(long timeout, TimeUnit unit) | Retrieves and removes an item from the tail of the queue, waiting the specified time, returning null if the time elapses before the item is available |
BlockingDeque interface extends Queue, Deque and BlockingQueue, so in BlockingDeque interface implementations all methods from above tables are available to use. See example below :
public class LinkedBlockingDequeExample {
public static void main(String[] args) {
try {
BlockingDeque<Integer> blockingDeque = new LinkedBlockingDeque<>();
blockingDeque.offer(91);
blockingDeque.offerFirst(5, 2, TimeUnit.MINUTES);
blockingDeque.offerLast(47, 100, TimeUnit.MICROSECONDS);
blockingDeque.offer(3, 4, TimeUnit.SECONDS);
System.out.println(blockingDeque.poll());
System.out.println(blockingDeque.poll(950, TimeUnit.MILLISECONDS));
System.out.println(blockingDeque.pollFirst(200, TimeUnit.NANOSECONDS));
System.out.println(blockingDeque.pollLast(1, TimeUnit.SECONDS));
} catch (InterruptedException e) {}
}
}