Open In App

DelayQueue drainTo() method in Java with Examples

Improve
Improve
Like Article
Like
Save
Share
Report

The drainTo(Collection<E> c) method of DelayQueue removes all available elements from this DelayQueue and adds them to the given collection passed as a parameter. This method is more efficient than repeatedly polling this DelayQueue. 
There are also possibilities of failure. If a DelayQueue attempts to drain a queue to itself, it will result in IllegalArgumentException. Further, the behavior of this operation is undefined if the specified collection is modified while the operation is in progress.
Syntax: 
 

public int drainTo (Collection<E> c)

Parameters: This method accepts one parameter c which represents the collection to transfer elements from DelayQueue.
Return Value: The function returns number of elements transferred.
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 illustrate the DelayQueue.drainTo() method:
Program 1: 
 

Java




// Java Program Demonstrate DelayQueue drainTo() method
 
import java.util.concurrent.*;
import java.util.*;
 
// The DelayObject for DelayQueue
// It must implement Delayed and
// its getDelay() and compareTo() method
class DelayObject implements Delayed {
 
    private String name;
    private long time;
 
    // Constructor of DelayObject
    public DelayObject(String name, long delayTime)
    {
        this.name = name;
        this.time = System.currentTimeMillis()
                    + delayTime;
    }
 
    // Implementing getDelay() method of Delayed
    @Override
    public long getDelay(TimeUnit unit)
    {
        long diff = time - System.currentTimeMillis();
        return unit.convert(diff, TimeUnit.MILLISECONDS);
    }
 
    // Implementing compareTo() method of Delayed
    @Override
    public int compareTo(Delayed obj)
    {
        if (this.time < ((DelayObject)obj).time) {
            return -1;
        }
        if (this.time > ((DelayObject)obj).time) {
            return 1;
        }
        return 0;
    }
 
    // Implementing toString() method of Delayed
    @Override
    public String toString()
    {
        return "\n{"
            + " " + name + ", time=" + time + "}";
    }
}
 
// Driver Class
public class GFG {
    public static void main(String[] args) throws InterruptedException
    {
 
        // create object of DelayQueue
        // using DelayQueue() constructor
        BlockingQueue<DelayObject> DQ
            = new DelayQueue<DelayObject>();
 
        // Add numbers to end of DelayQueue
        // using add() method
        DQ.add(new DelayObject("A", 1));
        DQ.add(new DelayObject("B", 2));
        DQ.add(new DelayObject("C", 3));
        DQ.add(new DelayObject("D", 4));
 
        System.out.println("Before drainTo():");
        System.out.println("DelayQueue: " + DQ);
 
        // create a ArrayList to pass as parameter to drainTo()
        ArrayList<DelayObject> array
            = new ArrayList<DelayObject>();
 
        // Apply drainTo method and pass array as parameter
        int response = DQ.drainTo(array);
        // print no of element passed
        System.out.println("\nNo of element passed: "
                           + response);
 
        // printing Arraylist and deque
        // after applying drainTo() method
        System.out.println("\nAfter drainTo():");
        System.out.println("DelayQueue : \n"
                           + DQ);
        System.out.println("ArrayList : \n"
                           + array);
    }
}


Output: 

Before drainTo():
DelayQueue: [
{ A, time=1546842375114}, 
{ B, time=1546842375115}, 
{ C, time=1546842375116}, 
{ D, time=1546842375117}]

No of element passed: 4

After drainTo():
DelayQueue : 
[]
ArrayList : 
[
{ A, time=1546842375114}, 
{ B, time=1546842375115}, 
{ C, time=1546842375116}, 
{ D, time=1546842375117}]

 

Program 2: Program to show exception thrown by drainTo() method. 
 

Java




// Java Program Demonstrate DelayQueue drainTo() method
 
import java.util.concurrent.*;
import java.util.*;
 
// The DelayObject for DelayQueue
// It must implement Delayed and
// its getDelay() and compareTo() method
class DelayObject implements Delayed {
 
    private String name;
    private long time;
 
    // Constructor of DelayObject
    public DelayObject(String name, long delayTime)
    {
        this.name = name;
        this.time = System.currentTimeMillis()
                    + delayTime;
    }
 
    // Implementing getDelay() method of Delayed
    @Override
    public long getDelay(TimeUnit unit)
    {
        long diff = time - System.currentTimeMillis();
        return unit.convert(diff, TimeUnit.MILLISECONDS);
    }
 
    // Implementing compareTo() method of Delayed
    @Override
    public int compareTo(Delayed obj)
    {
        if (this.time < ((DelayObject)obj).time) {
            return -1;
        }
        if (this.time > ((DelayObject)obj).time) {
            return 1;
        }
        return 0;
    }
 
    // Implementing toString() method of Delayed
    @Override
    public String toString()
    {
        return "\n{"
            + " " + name + ", time=" + time + "}";
    }
}
 
// Driver Class
public class GFG {
    public static void main(String[] args) throws InterruptedException
    {
 
        // create object of DelayQueue
        // using DelayQueue() constructor
        BlockingQueue<DelayObject> DQ
            = new DelayQueue<DelayObject>();
 
        // Add numbers to end of DelayQueue
        // using add() method
        DQ.add(new DelayObject("A", 1));
        DQ.add(new DelayObject("B", 2));
        DQ.add(new DelayObject("C", 3));
        DQ.add(new DelayObject("D", 4));
 
        // create a collection with null
        ArrayList<DelayObject> collection = null;
 
        // try to drain null DelayQueue to collection
        try {
            DQ.drainTo(collection);
        }
        catch (Exception e) {
            System.out.println("Exception: " + e);
        }
    }
}


Output: 

Exception: java.lang.NullPointerException

 

drainTo(Collection<E> col, int maxElements)

The drainTo(Collection<E> col, int maxElements) method removes at most the given number of available elements from this queue and adds them to the given collection. After transferring the elements, DelayQueue has only those elements which are not transferred to collection.
Syntax: 
 

drainTo(Collection<E> c, int maxElements)

Parameters: This method accepts two parameters:- 
 

  • c– It represents the collection to transfer elements from DelayQueue.s.
  • maxElements– This is of integer type and refers to the maximum number of elements to be transferred to the collection.

Return Value: The function returns number of elements transferred.
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 program illustrates drainTo(Collection<E> col, int maxElements) method of DelayQueue class:-
Program : 
 

Java




// Java Program Demonstrate DelayQueue drainTo() method
 
import java.util.concurrent.*;
import java.util.*;
 
// The DelayObject for DelayQueue
// It must implement Delayed and
// its getDelay() and compareTo() method
class DelayObject implements Delayed {
 
    private String name;
    private long time;
 
    // Constructor of DelayObject
    public DelayObject(String name, long delayTime)
    {
        this.name = name;
        this.time = System.currentTimeMillis()
                    + delayTime;
    }
 
    // Implementing getDelay() method of Delayed
    @Override
    public long getDelay(TimeUnit unit)
    {
        long diff = time - System.currentTimeMillis();
        return unit.convert(diff, TimeUnit.MILLISECONDS);
    }
 
    // Implementing compareTo() method of Delayed
    @Override
    public int compareTo(Delayed obj)
    {
        if (this.time < ((DelayObject)obj).time) {
            return -1;
        }
        if (this.time > ((DelayObject)obj).time) {
            return 1;
        }
        return 0;
    }
 
    // Implementing toString() method of Delayed
    @Override
    public String toString()
    {
        return "\n{"
            + " " + name + ", time=" + time + "}";
    }
}
 
// Driver Class
public class GFG {
    public static void main(String[] args) throws InterruptedException
    {
 
        // create object of DelayQueue
        // using DelayQueue() constructor
        BlockingQueue<DelayObject> DQ
            = new DelayQueue<DelayObject>();
 
        // Add numbers to end of DelayQueue
        // using add() method
        DQ.add(new DelayObject("A", 1));
        DQ.add(new DelayObject("B", 2));
        DQ.add(new DelayObject("C", 3));
        DQ.add(new DelayObject("D", 4));
 
        System.out.println("Before drainTo():");
        System.out.println("Number of elements in the DelayQueue: "
                           + DQ.size());
        System.out.println("DelayQueue: " + DQ);
 
        // create a ArrayList to pass as parameter to drainTo()
        ArrayList<DelayObject> array
            = new ArrayList<DelayObject>();
        // Initialize no of element passed to collection
        // using drainTo() method
        int noOfElement = 2;
        // Apply drainTo method and pass array as parameter
        int response = DQ.drainTo(array, noOfElement);
        // print no of element passed
        System.out.println("\nNo of element passed: "
                           + response);
 
        // printing Arraylist and deque
        // after applying drainTo() method
        System.out.println("\nAfter drainTo():");
        System.out.println("Number of elements in the DelayQueue: "
                           + DQ.size());
        System.out.println("DelayQueue : \n"
                           + DQ);
        System.out.println("ArrayList : \n"
                           + array);
    }
}


Output: 

Before drainTo():
Number of elements in the DelayQueue: 4
DelayQueue: [
{ A, time=1546842382382}, 
{ B, time=1546842382383}, 
{ C, time=1546842382384}, 
{ D, time=1546842382385}]

No of element passed: 2

After drainTo():
Number of elements in the DelayQueue: 2
DelayQueue : 
[
{ C, time=1546842382384}, 
{ D, time=1546842382385}]
ArrayList : 
[
{ A, time=1546842382382}, 
{ B, time=1546842382383}]

 



Last Updated : 07 May, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads