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() methodimportjava.util.concurrent.*;importjava.util.*;// The DelayObject for DelayQueue// It must implement Delayed and// its getDelay() and compareTo() methodclassDelayObject implementsDelayed {    privateString name;    privatelongtime;    // Constructor of DelayObject    publicDelayObject(String name, longdelayTime)    {        this.name = name;        this.time = System.currentTimeMillis()                    + delayTime;    }    // Implementing getDelay() method of Delayed    @Override    publiclonggetDelay(TimeUnit unit)    {        longdiff = time - System.currentTimeMillis();        returnunit.convert(diff, TimeUnit.MILLISECONDS);    }    // Implementing compareTo() method of Delayed    @Override    publicintcompareTo(Delayed obj)    {        if(this.time < ((DelayObject)obj).time) {            return-1;        }        if(this.time > ((DelayObject)obj).time) {            return1;        }        return0;    }    // Implementing toString() method of Delayed    @Override    publicString toString()    {        return"\n{"            + " "+ name + ", time="+ time + "}";    }}// Driver ClasspublicclassGFG {    publicstaticvoidmain(String[] args) throwsInterruptedException    {        // create object of DelayQueue        // using DelayQueue() constructor        BlockingQueue<DelayObject> DQ            = newDelayQueue<DelayObject>();        // Add numbers to end of DelayQueue        // using add() method        DQ.add(newDelayObject("A", 1));        DQ.add(newDelayObject("B", 2));        DQ.add(newDelayObject("C", 3));        DQ.add(newDelayObject("D", 4));        System.out.println("Before drainTo():");        System.out.println("DelayQueue: "+ DQ);        // create a ArrayList to pass as parameter to drainTo()        ArrayList<DelayObject> array            = newArrayList<DelayObject>();        // Apply drainTo method and pass array as parameter        intresponse = 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);    }} | 
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() methodimportjava.util.concurrent.*;importjava.util.*;// The DelayObject for DelayQueue// It must implement Delayed and// its getDelay() and compareTo() methodclassDelayObject implementsDelayed {    privateString name;    privatelongtime;    // Constructor of DelayObject    publicDelayObject(String name, longdelayTime)    {        this.name = name;        this.time = System.currentTimeMillis()                    + delayTime;    }    // Implementing getDelay() method of Delayed    @Override    publiclonggetDelay(TimeUnit unit)    {        longdiff = time - System.currentTimeMillis();        returnunit.convert(diff, TimeUnit.MILLISECONDS);    }    // Implementing compareTo() method of Delayed    @Override    publicintcompareTo(Delayed obj)    {        if(this.time < ((DelayObject)obj).time) {            return-1;        }        if(this.time > ((DelayObject)obj).time) {            return1;        }        return0;    }    // Implementing toString() method of Delayed    @Override    publicString toString()    {        return"\n{"            + " "+ name + ", time="+ time + "}";    }}// Driver ClasspublicclassGFG {    publicstaticvoidmain(String[] args) throwsInterruptedException    {        // create object of DelayQueue        // using DelayQueue() constructor        BlockingQueue<DelayObject> DQ            = newDelayQueue<DelayObject>();        // Add numbers to end of DelayQueue        // using add() method        DQ.add(newDelayObject("A", 1));        DQ.add(newDelayObject("B", 2));        DQ.add(newDelayObject("C", 3));        DQ.add(newDelayObject("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);        }    }} | 
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() methodimportjava.util.concurrent.*;importjava.util.*;// The DelayObject for DelayQueue// It must implement Delayed and// its getDelay() and compareTo() methodclassDelayObject implementsDelayed {    privateString name;    privatelongtime;    // Constructor of DelayObject    publicDelayObject(String name, longdelayTime)    {        this.name = name;        this.time = System.currentTimeMillis()                    + delayTime;    }    // Implementing getDelay() method of Delayed    @Override    publiclonggetDelay(TimeUnit unit)    {        longdiff = time - System.currentTimeMillis();        returnunit.convert(diff, TimeUnit.MILLISECONDS);    }    // Implementing compareTo() method of Delayed    @Override    publicintcompareTo(Delayed obj)    {        if(this.time < ((DelayObject)obj).time) {            return-1;        }        if(this.time > ((DelayObject)obj).time) {            return1;        }        return0;    }    // Implementing toString() method of Delayed    @Override    publicString toString()    {        return"\n{"            + " "+ name + ", time="+ time + "}";    }}// Driver ClasspublicclassGFG {    publicstaticvoidmain(String[] args) throwsInterruptedException    {        // create object of DelayQueue        // using DelayQueue() constructor        BlockingQueue<DelayObject> DQ            = newDelayQueue<DelayObject>();        // Add numbers to end of DelayQueue        // using add() method        DQ.add(newDelayObject("A", 1));        DQ.add(newDelayObject("B", 2));        DQ.add(newDelayObject("C", 3));        DQ.add(newDelayObject("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            = newArrayList<DelayObject>();        // Initialize no of element passed to collection        // using drainTo() method        intnoOfElement = 2;        // Apply drainTo method and pass array as parameter        intresponse = 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);    }} | 
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}]

 
                                    







