LinkedBlockingQueue drainTo() method in Java
Last Updated :
29 Nov, 2021
The drainTo(Collection col) method of LinkedBlockingQueue removes all available elements from this LinkedBlocking Queue and adds them to the given collection passed as a parameter.
drainTo(Collection<? super E> col)
The drainTo(Collection<? super E> col) method of LinkedBlockingQueue removes all of the elements from this queue and adds them to the given collection col. This is a more efficient way than repeatedly polling this queue.
There is also possibilities of failure encountered while attempting to add elements to collection c from the queue and due to that failure, elements is distributed between both collections when the associated exception is thrown. If a queue is tried to drainTo() to queue itself, then IllegalArgumentException will be thrown. If the specified collection is modified while the operation is in progress, the behavior of this operation is undefined. So for using such methods, one needs to take care of this type of situation to overcome exceptions.
Syntax:
public int drainTo(Collection<? super E> col)
Parameter: This method accepts one parameter col which represents the collection to transfer elements from LinkedBlockingQueue.
Return Value: This method returns the number of elements drained to collection from queue.
Exception: This method throws following exceptions:
- UnsupportedOperationException- if collection cannot able to add elements.
- ClassCastException- if class of element stops method to add element to collection.
- NullPointerException- if the collection is null
- IllegalArgumentException- if arguments of the method prevents it from being added to the specified collection
Below programs illustrates drainTo() method of LinkedBlockingQueue class:
Program 1:
Below program has a LinkedBlockingQueue which stores Employee objects. There is an ArrayList which will store all employee objects from LinkedBlockingQueue. So drainTo() is used with LinkedBlockingQueue to pass all employee from queue to ArrayList.
Java
// Java Program Demonstrate drainTo(Collection c)
// method of LinkedBlockingQueue.
import java.util.ArrayList;
import java.util.concurrent.LinkedBlockingQueue;
public class GFG {
// create a Employee Object with
// position and salary as an attribute
public class Employee {
public String name;
public String position;
public String salary;
Employee(String name, String position, String salary)
{
this.name = name;
this.position = position;
this.salary = salary;
}
@Override
public String toString()
{
return "Employee [name=" + name + ", position="
+ position + ", salary=" + salary + "]";
}
}
// Main Method
public static void main(String[] args)
{
GFG gfg = new GFG();
gfg.containsMethodExample();
}
public void containsMethodExample()
{
// define capacity of LinkedBlockingQueue
int capacity = 50;
// create object of LinkedBlockingQueue
LinkedBlockingQueue<Employee> linkedQueue
= new LinkedBlockingQueue<Employee>(capacity);
// create a ArrayList to pass as parameter to drainTo()
ArrayList<Employee> collection = new ArrayList<Employee>();
// add Employee object to queue
Employee emp1 = new Employee("Aman", "Analyst", "24000");
Employee emp2 = new Employee("Sachin", "Developer", "39000");
linkedQueue.add(emp1);
linkedQueue.add(emp2);
// printing Arraylist and queue
System.out.println("Before drainTo():");
System.out.println("LinkedBlockingQueue : \n"
+ linkedQueue.toString());
System.out.println("ArrayList : \n"
+ collection);
// Apply drainTo method and pass collection as parameter
int response = linkedQueue.drainTo(collection);
// print no of element passed
System.out.println("\nNo of element passed: " + response);
// printing Arraylist and queue after applying drainTo() method
System.out.println("\nAfter drainTo():");
System.out.println("LinkedBlockingQueue : \n"
+ linkedQueue.toString());
System.out.println("ArrayList : \n"
+ collection);
}
}
Output: Before drainTo():
LinkedBlockingQueue :
[Employee [name=Aman, position=Analyst, salary=24000],
Employee [name=Sachin, position=Developer, salary=39000]]
ArrayList :
[]
No of element passed: 2
After drainTo():
LinkedBlockingQueue :
[]
ArrayList :
[Employee [name=Aman, position=Analyst, salary=24000], Employee [name=Sachin, position=Developer, salary=39000]]
Program 2: Program to show exception thrown by drainTo() method.
Java
// Java Program Demonstrate
// drainTo(Collection C)
// method of LinkedBlockingQueue.
import java.util.ArrayList;
import java.util.concurrent.LinkedBlockingQueue;
public class GFG {
public static void main(String[] args)
throws InterruptedException
{
// define capacity of LinkedBlockingQueue
int capacityOfQueue = 4;
// create object of LinkedBlockingQueue
LinkedBlockingQueue<Integer>
linkedQueue = new LinkedBlockingQueue<Integer>(capacityOfQueue);
// add elements to queue
linkedQueue.put(85461);
linkedQueue.put(44648);
linkedQueue.put(45654);
// create a collection with null
ArrayList<Integer> add = null;
// try to drain null queue to collection
try {
linkedQueue.drainTo(add);
}
catch (Exception e) {
System.out.println("Exception: " + e);
}
}
}
Output: Exception: java.lang.NullPointerException
drainTo(Collection<? super E> col, int maxElements)
The drainTo(Collection<? super E> col, int maxElements) used to transfer fixed number elements which is passed as integer in drainTo() to collection which is also passed as parameter to method. After transferring the elements, LinkedBlockingQueue has only those elements which are not transferred to collection. This function is same as above function with some limitations to transfer fixed no of element.
Syntax:
public int drainTo(Collection<? super E> col, int maxElements)
Parameter: The method accepts two parameters:
- col- It represents the collection to transfer elements from LinkedBlockingQueue.
- maxElements- This is of integer type and refers to the maximum number of elements to be transferred to the collection.
Return Value: The method returns the number of elements drained to collection from queue.
Exception: This method throws following exceptions:
- UnsupportedOperationException - if collection cannot able to add elements.
- ClassCastException -if class of element stops method to add element to collection.
- NullPointerException - if the collection is null
- IllegalArgumentException - if arguments of the method prevents it from being added to the specified collection
Below programs illustrates drainTo(Collection<? super E> col, int maxElements) method of LinkedBlockingQueue class
Program 1:
Below program has a LinkedBlockingQueue which stores Employee objects and there is a HashSet in which will store all employee objects from LinkedBlockingQueue. So drainTo() of LinkedBlockingQueue is used to pass some employee from queue to ArrayList. So no of element to be transferred is passed in method as parameter.
Java
// Java program to demonstrate drainTo()
// method of LinkedBlockingQueue.
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
public class GFG {
// create a Employee Object with
// position and salary as attribute
public class Employee {
public String name;
public String position;
public String salary;
Employee(String name, String position, String salary)
{
this.name = name;
this.position = position;
this.salary = salary;
}
@Override
public String toString()
{
return "Employee [name=" + name + ", "
+ "position=" + position + ", salary=" + salary + "]";
}
}
// Main Method
public static void main(String[] args)
{
GFG gfg = new GFG();
gfg.containsMethodExample();
}
public void containsMethodExample()
{
// define capacity of LinkedBlockingQueue
int capacity = 10;
// create object of LinkedBlockingQueue
LinkedBlockingQueue<Employee> linkedQueue
= new LinkedBlockingQueue<Employee>(capacity);
// create a HashSet to pass as parameter to drainTo()
HashSet<Employee> collection = new HashSet<Employee>();
// add Employee object to queue
Employee emp1 = new Employee("Sachin", "Analyst", "40000");
Employee emp2 = new Employee("Aman", "Developer", "69000");
Employee emp3 = new Employee("Kajal", "Accountant", "39000");
linkedQueue.add(emp1);
linkedQueue.add(emp2);
linkedQueue.add(emp3);
// printing Arraylist and queue before applying drainTo() method
System.out.println("Before drainTo():");
System.out.println("No of Elements in Queue is " + linkedQueue.size());
System.out.println("Elements in Queue is as follows");
Iterator<Employee> listOfemp = linkedQueue.iterator();
while (listOfemp.hasNext())
System.out.println(listOfemp.next());
System.out.println("No of Elements in HashSet is " + collection.size());
System.out.println("Elements in HashSet is as follows:");
for (Employee emp : collection)
System.out.println(emp);
// Initialize no of element passed to collection
// using drainTo() method
int noOfElement = 2;
// Apply drainTo method and pass collection as parameter
int response = linkedQueue.drainTo(collection, noOfElement);
// print no of element passed
System.out.println("\nNo of element passed: " + response);
// printing Arraylist and queue after applying drainTo() method
System.out.println("\nAfter drainTo():");
System.out.println("No of Elements in Queue is " + linkedQueue.size());
System.out.println("Elements in Queue is as follows");
listOfemp = linkedQueue.iterator();
while (listOfemp.hasNext())
System.out.println(listOfemp.next());
System.out.println("No of Elements in HashSet is " + collection.size());
System.out.println("Elements in HashSet is as follows:");
for (Employee emp : collection)
System.out.println(emp);
}
}
Output: Before drainTo():
No of Elements in Queue is 3
Elements in Queue is as follows
Employee [name=Sachin, position=Analyst, salary=40000]
Employee [name=Aman, position=Developer, salary=69000]
Employee [name=Kajal, position=Accountant, salary=39000]
No of Elements in HashSet is 0
Elements in HashSet is as follows:
No of element passed: 2
After drainTo():
No of Elements in Queue is 1
Elements in Queue is as follows
Employee [name=Kajal, position=Accountant, salary=39000]
No of Elements in HashSet is 2
Elements in HashSet is as follows:
Employee [name=Sachin, position=Analyst, salary=40000]
Employee [name=Aman, position=Developer, salary=69000]
Reference:
Similar Reads
LinkedBlockingQueue Class in Java
The LinkedBlockingQueue in Java is part of the java.util.concurrent package and implements the BlockingQueue interface. It provides a thread-safe, bounded, or unbounded queue used for managing tasks in a producer-consumer scenario. This queue can be used in multithreaded environments where one threa
8 min read
LinkedBlockingQueue clear() method in Java
The clear() method of LinkedBlockingQueue removes all of the elements from this queue. After applying this method the queue will become empty. Syntax: public void clear() Below programs illustrates clear() method of LinkedBlockingQueue class: Program 1: Java // Java Program Demonstrate clear() // me
2 min read
LinkedBlockingQueue iterator() method in Java
The iterator() method of LinkedBlockingQueue returns an iterator of the same elements, as this LinkedBlockingQueue, in a proper sequence. The elements returned from this method contains all the elements in order from first(head) to last(tail) of LinkedBlockingQueue. The returned iterator is weakly c
3 min read
LinkedBlockingQueue drainTo() method in Java
The drainTo(Collection col) method of LinkedBlockingQueue removes all available elements from this LinkedBlocking Queue and adds them to the given collection passed as a parameter. drainTo(Collection<? super E> col) The drainTo(Collection<? super E> col) method of LinkedBlockingQueue rem
7 min read
LinkedBlockingQueue | offer() Method in JAVA
There is two types of offer() method for LinkedBlockingQueue class : offer(E e, long timeout, TimeUnit unit) The offer(E e, long timeout, TimeUnit unit) method of LinkedBlockingQueue inserts the element passed as parameter to method at the tail of this LinkedBlockingQueue if queue is not full. It wi
6 min read
LinkedBlockingQueue peek() method in Java
The peek() method of LinkedBlockingQueue returns the head of the LinkedBlockingQueue. It retrieves the value of the head of LinkedBlockingQueue but does not remove it. If the LinkedBlockingQueue is empty then this method returns null. Syntax: public E peek() Return Value: This method returns the hea
3 min read
LinkedBlockingQueue poll() method in Java
There is two types of poll() method in LinkedBlockingQueue. poll() The poll() method of LinkedBlockingQueue returns the head of LinkedBlockingQueue by removing that element from queue. It can be said that this method retrieves and removes element from head of this LinkedBlockingQueue. If queue is em
6 min read
LinkedBlockingQueue put() method in Java with Examples
The put(E e) method of LinkedBlockingQueue inserts element passed as parameter to method at the tail of this LinkedBlockingQueue, if queue is not full. If the queue is full, then this method will wait for space to become available and after space is available, it inserts the element to LinkedBlockin
3 min read
LinkedBlockingQueue remainingCapacity() method in Java
The remainingCapacity() method of LinkedBlockingQueue returns the number of more elements that can be added to LinkedBlockingQueue without blocking. The Capacity returned arises three cases: If remaining Capacity is Zero, then no more elements can be added to the LinkedBlockingQueue.If remaining Cap
3 min read
LinkedBlockingQueue remove() method in Java
The remove(Object obj) method of LinkedBlockingQueue removes only one instance of the given Object, passed as parameter, from this LinkedBlockingQueue if it is present. It removes an element e such that obj.equals(e) and if this queue contains one or more instance of element e. This method returns t
4 min read