LinkedBlockingQueue Java Example
February 15, 2013
On this page we will provide example of LinkedBlockingQueue in java. LinkedBlockingQueue has been introduced in JDK 1.5. It belongs to java.util.concurrent package. LinkedBlockingQueue is a BlockingQueue which uses linked node. LinkedBlockingQueue can be instantiated as bounded as well unbounded. We will discuss here LinkedBlockingQueue with example.
BlockingQueue
BlockingQueue
is a Queue
but with some different features. While retrieving element from BlockingQueue
, thread waits if it is empty. Once the element is added in BlockingQueue
, thread is unblocked retrieving element successfully. Same happens when thread is trying to add element in BlockingQueue
. If the size of BlockingQueue
is limited and it is already full, then thread waits until it gets space to add element.
LinkedBlockingQueue
LinkedBlockingQueue
implements BlockingQueue
and works on the basis of linked node. It can be instantiated as bounded as well as unbounded. The elements in LinkedBlockingQueue
are managed as First-In First-Out (FIFO) rule. Find the details of some methods of this class.
offer(E e): It inserts the element at the tail of queue without exceeding
LinkedBlockingQueue
size. On success it returns true otherwise false.
put(E e): Inserts the element at the tail of the queue and waits for space if necessary.
peek(): It retrieves the head of the queue without deleting it and returns null if empty.
poll(): It retrieves and removes the head of the queue and returns null if empty.
remove(Object o): Removes the specified element from the queue.
take(): Retrieves and removes the head of the queue and waits if necessary.
Complete Example of LinkedBlockingQueue
LinkedBlockingQueueTest.java
package com.concretepage.concurrent; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; public class LinkedBlockingQueueTest { private final LinkedBlockingQueue<String> lbqueue = new LinkedBlockingQueue<String>(); class ThreadA implements Runnable { @Override public void run() { lbqueue.offer("AAAA"); lbqueue.offer("BBBB"); lbqueue.offer("CCCC"); lbqueue.offer("DDDD"); lbqueue.offer("EEEE"); } } class ThreadB implements Runnable { @Override public void run() { try { for (int i=0; i < 5; i++) { System.out.println(lbqueue.take()); } } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String... args) { ExecutorService service = Executors.newFixedThreadPool(2); LinkedBlockingQueueTest linkedBlockingQueueTest = new LinkedBlockingQueueTest(); ThreadA threadA = linkedBlockingQueueTest.new ThreadA(); ThreadB threadB = linkedBlockingQueueTest.new ThreadB(); service.execute(threadA); service.execute(threadB); service.shutdown(); } }
AAAA BBBB CCCC DDDD EEEE