Java Program to Implement LinkedBlockingQueue API
Last Updated :
16 Mar, 2023
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:
- public LinkedBlockingQueue() - Creates a LinkedBlockingQueue with a capacity of Integer.MAX_VALUE.
- public LinkedBlockingQueue(Collection<? extends E> c) - Creates a LinkedBlockingQueue of capacity Integer.MAX_VALUE, initially containing the elements of the specified Collection.
- 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 the 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);
}
}
OutputThe 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]
Methods:
Method | Type | Description |
---|
clear() | void | Removes all the elements of the LinkedBlockingQueue |
contains(Object O) | boolean | Returns true if the queue contains the specified element. |
iterator() | Iterator(<E>) | Returns an iterator over the elements in the queue. |
offer(E e) | boolean | Inserts 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) | boolean | Inserts the specified element at the tail of the queue and wait for the specified time for the space to become available. |
peek() | E | Retrieves, but does not remove, the head of the queue. |
poll() | E | Retrieves and removes the head of the queue. |
put(E e) | void | Inserts the specified element at the tail of this queue, waiting if necessary for space to become available. |
remainingCapacity() | int | Returns the number of additional elements that this queue can ideally accept without blocking. |
size() | int | Returns the size of the queue |
toArray() | Object[] | Converts the queue to an array |
drainTo(Collection<? super E> c) | int | Removes all available elements from the queue and adds them to the specified collection. |
take() | E | Retrieves and removes the head of this queue, waiting if necessary until an element becomes available. |
remove(Object O) | boolean | Removes the specified element from the queue, if it is present. |
Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Java Programs - Java Programming Examples In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read