Skip to content
Related Articles

Related Articles

Improve Article

Java Program to Implement LinkedBlockingQueue API

  • Difficulty Level : Easy
  • Last Updated : 17 Jun, 2021

LinkedBlockingQueue API is an optionally-bounded queue based on linked nodes. It orders the elements in FIFO(First In First Out) order. The head of this queue is the element that has been there in the queue for the longest time and the tail of the queue is the element that has been in the queue for the shortest time.  New elements are inserted at the tail of the queue, and the queue retrieval operations obtain elements at the head of the queue. It belongs to java.util.concurrent package. It extends Object, AbstractCollection and AbstractQueue classes.

The capacity argument serves as a way to prevent excessive queue expansion. The capacity (if not specified) is equal to Integer.MAX_VALUE. Linked nodes are dynamically created upon each insertion unless this would bring the queue above capacity. 

LinkedBlockingQueue API is a member of Java Collection Framework.

All implemented interfaces:

1. Serializable
2. Iterable<E>
3. Collection<E>
4. BlockingQueue<E>
5. Queue<E>

Parameters: E — The type of elements in the collection



Syntax:

public class LinkedBlockingQueue<E> extends AbstractQueue<E>
implements BlockingQueue<E>, Serializable

Constructors:

  1. public LinkedBlockingQueue() – Creates a LinkedBlockingQueue with a capacity of Integer.MAX_VALUE.
  2. public LinkedBlockingQueue(Collection<? extends E> c) – Creates a LinkedBlockingQueue of capacity Integer.MAX_VALUE, initially containing the elements of the specified Collection.
  3. public LinkedBlockingQueue(int capacity) – Creates a LinkedBlockingQueue with the given capacity.

Implementation:

Example

Java




// Java Program to Implement LinkedBlockingQueue API
 
import java.util.Collection;
import java.util.Iterator;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
 
public class BlockingQueue<E> {
    private LinkedBlockingQueue<E> q;
 
    // Creates a LinkedBlockingQueue with a size of
    // Integer.MAX_VALUE.
    public BlockingQueue()
    {
        q = new LinkedBlockingQueue<E>();
    }
 
    // Creates a LinkedBlockingQueue initially containing
    // the elements of the given collection
    public BlockingQueue(Collection<? extends E> c)
    {
        q = new LinkedBlockingQueue<E>(c);
    }
 
    // Creates a LinkedBlockingQueue with the given size
    public BlockingQueue(int size)
    {
        q = new LinkedBlockingQueue<E>(size);
    }
 
    // Returns true if the queue contains the given element
    public boolean contains(Object o)
    {
        return q.contains(o);
    }
 
    // Removes all elements from the queue and adds them to
    // the given collection.
    public int drainTo(Collection<? super E> c)
    {
        return q.drainTo(c);
    }
 
    //  Removes the elements from the queue and adds them to
    //  the given collection.
    public int drainTo(Collection<? super E> c, int maxEle)
    {
        return q.drainTo(c, maxEle);
    }
 
    // Returns an iterator over the elements in the queue
    public Iterator<E> iterator() { return q.iterator(); }
 
    // removes all the elements from the queue.
    void clear() { q.clear(); }
 
    // Inserts the given element at the end of the queue,
    // returning true upon inserting and false if the queue
    // is full.
    public boolean offer(E e) { return q.offer(e); }
 
    // inserts then given element at the end and wait for
    // the given time for the space to become available
    public boolean offer(E e, long timeout, TimeUnit unit)
        throws InterruptedException
    {
        return q.offer(e, timeout, unit);
    }
 
    // Retrieves, but does not remove, the head of the
    // queue, or returns null if this queue is empty.
    public E peek() { return q.peek(); }
 
    //  Retrieves and removes the head of the queue
    public E poll() { return q.poll(); }
 
    // Retrieves and removes the head of the queue and wait
    // for the specified time for the element to become
    // available.
    public E poll(long tout, TimeUnit un)
        throws InterruptedException
    {
        return q.poll(tout, un);
    }
 
    // Returns the number of additional elements that the
    // queue can contain without blocking.
    public int remainingCapacity()
    {
        return q.remainingCapacity();
    }
 
    // Removes the specified element from the queue
    public boolean remove(Object o) { return q.remove(o); }
 
    // Returns the number of elements in the queue
    public int size() { return q.size(); }
 
    // Inserts the given element at the end of the queue,
    // wait for space to become available
    public void put(E e) throws InterruptedException
    {
        q.put(e);
    }
 
    // Retrieves and removes the head of the queue wait till
    // an element becomes available
    public E take() throws InterruptedException
    {
        return q.take();
    }
 
    // Returns an array containing all the elements in the
    // queue.
    public Object[] toArray() { return q.toArray(); }
 
    // Returns an array containing all of the elements in
    // the queue
    public <T> T[] toArray(T[] a) { return q.toArray(a); }
 
    // Returns a string representation of th collection.
    public String toString() { return q.toString(); }
 
    public static void main(String[] args)
    {
        BlockingQueue<Integer> q
            = new BlockingQueue<Integer>();
        try {
            q.put(1);
            q.put(2);
            q.put(3);
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
 
        System.out.println(
            "The elements of the LinkedBlockingQueue is ");
 
        Iterator<Integer> i = q.iterator();
 
        while (i.hasNext()) {
            System.out.print(i.next() + "\t");
        }
        System.out.println();
 
        System.out.println("The remaining capacity is "
                           + q.remainingCapacity());
 
        System.out.println("3 removed " + q.remove(3));
 
        q.offer(6);
        q.offer(7);
 
        System.out.println(
            "The peak element of the LinkedBlockingQueue is "
            + q.peek());
 
        System.out.println(
            "The peak element of the LinkedBlockingQueue is "
            + q.poll());
 
        System.out.println(
            "The LinkedBlockingQueue contains 4 :"
            + q.contains(4));
 
        System.out.println(
            "The LinkedBlockingQueue contains 1 :"
            + q.contains(1));
 
        System.out.println(
            "The size of the LinkedBlockingQueue is "
            + q.size());
 
        System.out.println(q);
    }
}
Output
The elements of the LinkedBlockingQueue is 
1    2    3    
The remaining capacity is 2147483644
3 removed true
The peak element of the LinkedBlockingQueue is 1
The peak element of the LinkedBlockingQueue is 1
The LinkedBlockingQueue contains 4 :false
The LinkedBlockingQueue contains 1 :false
The size of the LinkedBlockingQueue is 3
[2, 6, 7]

 
 

Output
The elements of the LinkedBlockingQueue is 
1    2    3    
The remaining capcity is 2147483644
3 removed true
The peak element of the LinkedBlockingQueue is 1
The peak element of the LinkedBlockingQueue is 1
The LinkedBlockingQueue contains 4 :false
The LinkedBlockingQueue contains 1 :false
The size of the LinkedBlockingQueue is 3
[2, 6, 7]

 

Methods:

 

MethodTypeDescription
clear()void Removes all the elements of the LinkedBlockingQueue
contains(Object O)booleanReturns true if the queue contains the specified element.
iterator()Iterator(<E>)Returns an iterator over the elements in the queue.
offer(E e)booleanInserts the specified element at the tail of this queue if it is possible and returns true upon success otherwise false.
offer(E e, long timeout, TimeUnit unit)booleanInserts the specified element at the tail of the queue and wait for the specified time for the space to become available.
peek()ERetrieves, but does not remove, the head of the queue.
poll()ERetrieves and removes the head of the queue.
put(E e)voidInserts the specified element at the tail of this queue, waiting if necessary for space to become available.
remainingCapacity()intReturns the number of additional elements that this queue can ideally accept without blocking.
size()intReturns the size of the queue
toArray()Object[]Converts the queue to an array
drainTo(Collection<? super E> c)intRemoves all available elements from the queue and adds them to the specified collection.
take()ERetrieves and removes the head of this queue, waiting if necessary until an element becomes available.
remove(Object O)booleanRemoves the specified element from the queue, if it is present.

 

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :