Java LinkedBlockingQueue
What is Java LinkedBlockingQueue?
- Java LinkedBlockingQueue is a class in the Java Collections Framework that implements the BlockingQueue interface.
- It is a thread-safe data structure that allows multiple threads to access and manipulate a queue of elements. Elements are added to the back of the queue, and removed from the front of the queue.
- LinkedBlockingQueue is based on a linked node structure, where each node in the queue contains an element and a reference to the next node.
- To understand the Java LinkedBlockingQueue, Read the Complete Article.
Steps to Create Java LinkedBlockingQueue
1. Import the LinkedBlockingQueue class:
import java.util.concurrent.LinkedBlockingQueue;
2. Create an instance of the LinkedBlockingQueue class:
LinkedBlockingQueuequeue = new LinkedBlockingQueue<>();
3. Add elements to the queue using the add() method:
queue.add("Element 1"); queue.add("Element 2");
4. Alternatively, you can use the put() method to add elements to the queue. The put() method will block if the queue is full:
queue.put("Element 3");
5. Remove elements from the queue using the remove() method:
String element = queue.remove();
5.Alternatively, you can use the take() method to remove elements from the queue. The take() method will block if the queue is empty:
String element = queue.take();
Methods of LinkedBlockingQueue
- add(E e): Adds the specified element to the end of the queue. Throws an exception if the queue is full.
- offer(E e): Adds the specified element to the end of the queue. Returns true if the element was added successfully, false otherwise.
- put(E e): Adds the specified element to the end of the queue. If the queue is full, blocks until space becomes available.
- take(): Removes and returns the head of the queue. If the queue is empty, blocks until an element becomes available.
- poll(): Removes and returns the head of the queue, or returns null if the queue is empty.
- peek(): Returns the head of the queue without removing it, or returns null if the queue is empty.
- size(): Returns the number of elements in the queue.
- remainingCapacity(): Returns the number of additional elements that the queue can hold.
- contains(Object o): Returns true if the queue contains the specified element, false otherwise.
- remove(Object o): Removes the first occurrence of the specified element from the queue, if it is present.
- toArray(): Returns an array containing all of the elements in the queue, in the same order as they appear in the queue.
- clear(): Removes all elements from the queue.
Let’s look at the Java LinkedBlockingQueue to perform certain operations.
Example 1: Java Program to Insert Elements in LinkedBlockingQueue
Run
import java.util.concurrent.LinkedBlockingQueue; public class Main{ public static void main(String[] args) { // Create a LinkedBlockingQueue LinkedBlockingQueuequeue = new LinkedBlockingQueue (); // Add elements to the queue queue.add("element 1"); queue.add("element 2"); queue.add("element 3"); // Print the elements in the queue System.out.println("Elements in the queue:"); for (String element : queue) { System.out.println(element); } } }
Output
Elements in the queue: element 1 element 2 element 3
Explanation:
In this example, we create a LinkedBlockingQueue and add three elements to it using the add method. We then print the elements in the queue using a for loop that iterates over the elements in the queue.
Note that the LinkedBlockingQueue class implements the Iterable interface, which means that you can use a for loop to iterate over the elements in the queue.
Example 2 : Java Program to remove Elements in LinkedBlockingQueue
Run
import java.util.concurrent.LinkedBlockingQueue; public class Main { public static void main(String[] args) { // Create a LinkedBlockingQueue LinkedBlockingQueuequeue = new LinkedBlockingQueue (); // Add elements to the queue queue.add("element 1"); queue.add("element 2"); queue.add("element 3"); // Remove elements from the queue String element1 = queue.poll(); String element2 = queue.poll(); String element3 = queue.poll(); // Print the removed elements System.out.println("Removed elements:"); System.out.println(element1); System.out.println(element2); System.out.println(element3); // Print the elements remaining in the queue System.out.println("Elements remaining in the queue:"); for (String element : queue) { System.out.println(element); } } }
Output
Removed elements: element 1 element 2 element 3 Elements remaining in the queue:
Explanation:
In this example, we create a LinkedBlockingQueue and add three elements to it using the add method. We then remove the elements from the queue using the poll method and store them in variables.
We print the removed elements using System.out.println statements, and then print the elements remaining in the queue using a for loop that iterates over the elements in the queue.
Example 3:Java Program to Access Elements in LinkedBlockingQueue
Run
import java.util.concurrent.LinkedBlockingQueue; public class Main { public static void main(String[] args) { // Create a LinkedBlockingQueue LinkedBlockingQueue queue = new LinkedBlockingQueue(); // Add elements to the queue queue.add("element 1"); queue.add("element 2"); queue.add("element 3"); // Access the head element of the queue String headElement = queue.peek(); // Print the head element System.out.println("Head element: " + headElement); // Check if the queue contains a specific element boolean containsElement2 = queue.contains("element 2"); // Print the result if (containsElement2) { System.out.println("The queue contains element 2"); } else { System.out.println("The queue does not contain element 2"); } } }
Output
Head element: element 1 The queue contains element 2
Explanation:
In this example, we create a LinkedBlockingQueue and add three elements to it using the add method. We then access the head element of the queue using the peek method and store it in a variable. We print the head element using a System.out.println statement.
We then check if the queue contains a specific element using the contains method and store the result in a boolean variable. We print the result using a System.out.println statement.
This shows that we were able to access elements in the queue using the peek and contains methods. Note that the peek method returns null if the queue is empty, so it's a good idea to check if the result is null before using it.
Java put() and take() Methods
Example 4: Java Program to Take() Method in Java LinkedBlockingQueue
Run
import java.util.concurrent.LinkedBlockingQueue; public class Main { public static void main(String[] args) throws InterruptedException { // Create a LinkedBlockingQueue LinkedBlockingQueuequeue = new LinkedBlockingQueue (); // Add elements to the queue queue.add("element 1"); queue.add("element 2"); queue.add("element 3"); // Take elements from the queue using take() method String element1 = queue.take(); String element2 = queue.take(); String element3 = queue.take(); // Print the elements System.out.println("Element 1: " + element1); System.out.println("Element 2: " + element2); System.out.println("Element 3: " + element3); } }
Output
Element 1: element 1 Element 2: element 2 Element 3: element 3
Explanation:
In this example, we create a LinkedBlockingQueue and add three elements to it using the add method. We then use the take method to remove elements from the queue and store them in variables. The take method blocks (i.e., waits) until an element becomes available in the queue.
We then print the three elements using System.out.println statements.
This shows that we were able to use the take method to remove elements from the queue in the correct order.
Note that if the queue is empty, the take method will block until an element becomes available. In this case, it's a good idea to use a try-catch block to handle the InterruptedException that may be thrown by the take method
Example 5: Java Program to use Put() Method in LinkedBlockingQueue
import java.util.concurrent.LinkedBlockingQueue; public class Main { public static void main(String[] args) throws InterruptedException { // Create a LinkedBlockingQueue with capacity 2 LinkedBlockingQueue queue = new LinkedBlockingQueue(2); // Add elements to the queue using put() method queue.put("element 1"); System.out.println("Added element 1"); queue.put("element 2"); System.out.println("Added element 2"); // Try to add a third element to the queue using put() method System.out.println("Trying to add element 3..."); queue.put("element 3"); // This line won't be reached because the previous line will block System.out.println("Added element 3"); } }
Output
LinkedHashMap: Apple: 1 Samsung: 2 Nokia: 3 HashMap: Apple: 1 Samsung: 2 Nokia: 3
Explanation:
In this example, we create a LinkedBlockingQueue with a capacity of 2 and add two elements to it using the put method. We then try to add a third element to the queue using put. Since the queue is already full, the put method will block (i.e., wait) until space becomes available in the queue.
This shows that the first two elements were added to the queue successfully, and that the put method blocked when we tried to add a third element.
Note that if the queue is full, the put method will block until space becomes available. In this case, it's a good idea to use a try-catch block to handle the InterruptedException that may be thrown by the put method.
Why use LinkedBlockingQueue?
Java LinkedBlockingQueue is a thread-safe implementation of the BlockingQueue interface in Java, which means that it can be used in multi-threaded applications where multiple threads may need to add or remove elements from the queue simultaneously.
Some reasons to use LinkedBlockingQueue are:
- Thread safety: As mentioned above, LinkedBlockingQueue is thread-safe, which means that multiple threads can access the queue at the same time without causing any concurrency issues.
- Blocking behavior: LinkedBlockingQueue is a blocking queue, which means that if a thread tries to remove an element from an empty queue, it will block (i.e., wait) until an element becomes available. Similarly, if a thread tries to add an element to a full queue, it will block until there is space available in the queue. This can be useful in scenarios where you want to control the flow of data between threads.
- FIFO ordering: LinkedBlockingQueue maintains the order of elements in the queue according to first-in, first-out (FIFO) ordering. This means that the order in which elements are added to the queue is preserved when they are removed.
- No size limit: LinkedBlockingQueue can grow dynamically as needed, which means that there is no fixed limit to the number of elements that can be added to the queue. This can be useful in scenarios where you don’t know the maximum number of elements that will be added to the queue.
Overall, LinkedBlockingQueue is a versatile and flexible data structure that can be useful in a wide range of multi-threaded applications.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment