Friday, June 17, 2011


LinkedBlockingQueue class is an optional boundless blocking queue which is based on linked nodes.

The elements of this queue are ordered in FIFO (first-in-first-out). In this queue the element that has been the longest time on the queue is the head element, and the element that has been the shortest time on the queue is the tail element of the queue. Insertion of an element in this queue is happened at tail and the element is retrieved from the head position.

As LinkedBlockingQueue is defined earlier that it is an optional boundless blocking queue so it can increase upto the value if there is no lower bound is specified and the capacity is equal to the Integer.MAX_VALUE. The throughput of Linked queues are maximum than the array-based queues whereas in the most simultaneous applications the performance is less predictable.
All of the optional methods of the Collection and Iterator interfaces are implemented by this class and its iterator.


public class LinkedBlockingQueue<E>
Parameter description
E : It is the element's type that's held by this queue.
Constructor of LinkedBlockingQueue class are :
  • LinkedBlockingQueue() : This constructor makes a LinkedBlockingQueue with the capability of Integer.MAX_VALUE.
  • LinkedBlockingQueue(E> c) : This constructor makes a LinkedBlockingQueue with the capability of Integer.MAX_VALUE, keeps the elements of a particular collection that are appended in the traversing order of the collection's iterator.
  • LinkedBlockingQueue(int capacity) : With the constant(given) capacity this constructor makes a LinkedBlockingQueue.
Example :
Here we give a simple example which will demonstrate you how can methods of LinkedBlockingQueue class be implemented.

public class LinkedBlockingQueueDemo {
  public static void main(String args[]) {
    LinkedBlockingQueue lbq = new LinkedBlockingQueue();
    System.out.println("Elements of 1st queue = " + lbq);
    LinkedBlockingQueue lbq1 = new LinkedBlockingQueue(10);
    // drainTo() method
    int i = lbq.drainTo(lbq1);
    System.out.println(i+ " elements are removed from 1st queue and 
                               add to the 2nd queue.");
    System.out.println("Therefore elements 
                             of 2nd queue = " + lbq1);
    // remainingCapacity() method
    int i1 = lbq1.remainingCapacity();
    System.out.println("The remaining element that can 
                     be inserted into 2nd queue = "+ i1);

No comments:

Post a Comment