DelayQueue Class in Java with Example - GeeksforGeeks

20 May, 2021
The DelayQueue class is a member of the Java Collections Framework. It belongs to java.util.concurrent package. DelayQueue implements the BlockingQueue interface. DelayQueue is a specialized Priority Queue that orders elements based on their delay time. It means that only those elements can be taken from the queue whose time has expired. DelayQueue head contains the element that has expired in the least time. If no delay has expired, then there is no head and the poll will return null. DelayQueue accepts only those elements that belong to a class of type Delayed or those implement java.util.concurrent.Delayed interface. The DelayQueue blocks the elements internally until a certain delay has expired. DelayQueue implements the getDelay(TimeUnit.NANOSECONDS) method to return the remaining delay time. The TimeUnit instance passed to the getDelay() method is an Enum that tells which time unit the delay should be returned in. The TimeUnit enum can take DAYS, HOURS, MINUTES, SECONDS, MILLISECONDS, MICROSECONDS, NANOSECONDS. This queue does not permit null elements. This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces. The Iterator provided in method iterator() is not guaranteed to traverse the elements of the DelayQueue in any particular order. 
// Declaration of Delayed interface
public interface Delayed extends Comparable<Delayed>
{
/**
    * Returns the remaining delay associated with this object, in the
    * given time unit.
    *
    * @param unit the time unit
    *
    * @return the remaining delay; zero or negative values indicate
    * that the delay has already elapsed
    */
   long getDelay(TimeUnit unit);
}
The Hierarchy of DelayQueue
It implements Iterable<E>, Collection<E>, BlockingQueue<E>, Queue<E> interfaces.
Class Declaration:  
public class DelayQueue<E extends Delayed> extends AbstractQueue<E> implements BlockingQueue<E> 
Here, E is the type of element maintained by this collection.
To construct a DelayQueue, we need to import it from java.util.concurrent.DelayQueue.
1. DelayQueue(): This constructor is used to construct an empty DelayQueue.
DelayQueue<E> dq = new DelayQueue<E>();
2. DelayQueue(Collection<E> c): This constructor is used to construct a DelayQueue with the elements of the Collection of Delayed instances passed as the parameter.
DelayQueue<E> dq = new DelayQueue(Collection<E> c);
Below is a sample program to illustrate DelayQueue in Java: 
Java
// Java Program Demonstrate DelayQueue import java.util.concurrent.*;import java.util.*; // The DelayObject for DelayQueue// It must implement Delayed and// its getDelay() and compareTo() methodclass 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=" + name            + ", time=" + time            + "}";    }} // Driver Classpublic 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        DQ.add(new DelayObject("A", 1));        DQ.add(new DelayObject("B", 2));        DQ.add(new DelayObject("C", 3));        DQ.add(new DelayObject("D", 4));         // print DelayQueue        System.out.println("DelayQueue: "                           + DQ);         // create object of DelayQueue        // using DelayQueue(Collection c)        // constructor        BlockingQueue<DelayObject> DQ2            = new DelayQueue<DelayObject>(DQ);         // print DelayQueue        System.out.println("DelayQueue: "                           + DQ2);    }}
DelayQueue: [
{name=A, time=1543472836003}, 
{name=B, time=1543472836004}, 
{name=C, time=1543472836005}, 
{name=D, time=1543472836006}]
DelayQueue: [
{name=A, time=1543472836003}, 
{name=B, time=1543472836004}, 
{name=C, time=1543472836005}, 
{name=D, time=1543472836006}]
 
Below is a sample program to illustrate DelayQueue methods in Java:
Java
// Java Program Demonstrate DelayQueue methods import java.util.concurrent.*;import java.util.*; // The DelayObject for DelayQueue// It must implement Delayed and// its getDelay() and compareTo() methodclass 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=" + name            + ", time=" + time            + "}";    }} // Driver Classpublic 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));         // print queue        System.out.println("DelayQueue: "                           + DQ);         // print the head using peek() method        System.out.println("Head of DelayQueue: "                           + DQ.peek());         // print the size using size() method        System.out.println("Size of DelayQueue: "                           + DQ.size());         // remove the head using poll() method        System.out.println("Head of DelayQueue: "                           + DQ.poll());         // print the size using size() method        System.out.println("Size of DelayQueue: "                           + DQ.size());         // clear the DelayQueue using clear() method        DQ.clear();        System.out.println("Size of DelayQueue"                           + " after clear: "                           + DQ.size());    }}
DelayQueue: [
{name=A, time=1543472845012}, 
{name=B, time=1543472845013}, 
{name=C, time=1543472845014}, 
{name=D, time=1543472845015}]

Head of DelayQueue: 
{name=A, time=1543472845012}

Size of DelayQueue: 4

Head of DelayQueue: 
{name=A, time=1543472845012}

Size of DelayQueue: 3

Size of DelayQueue after clear: 0
 
1. Adding Elements
The add(E e) method of DelayQueue class in Java is used to insert the given element into the delay queue and returns true if the element has been successfully inserted. 
Java
// Java program to illustrate the adding// elements to the DelayQueue import java.util.concurrent.DelayQueue;import java.util.concurrent.Delayed;import java.util.concurrent.TimeUnit; public class AddingElementsExample {    public static void main(String args[])    {        // Create a DelayQueue instance        DelayQueue<Delayed> queue            = new DelayQueue<Delayed>();         // Create an instance of Delayed        Delayed obj = new Delayed() {            public long getDelay(TimeUnit unit)            {                return 24; // some value is returned            }             public int compareTo(Delayed o)            {                if (o.getDelay(TimeUnit.DAYS)                    > this.getDelay(TimeUnit.DAYS))                    return 1;                else if (o.getDelay(TimeUnit.DAYS)                         == this.getDelay(TimeUnit.DAYS))                    return 0;                return -1;            }        };         // Use the add() method to add obj to        // the empty DelayQueue instance        queue.add(obj);         // printing size of the queue to the console        System.out.println("Size of the queue : "                           + queue.size());    }}
  
Size of the queue : 1
 
2. Removing Elements
 
The remove() method of DelayQueue class in Java is used to remove a single instance of the given object say obj from this DelayQueue if it is present. It returns true if the given element is removed successfully otherwise it returns false.  
 
Java
// Java Program to illustrate the removing// elements of DelayQueue class import java.util.concurrent.DelayQueue;import java.util.concurrent.Delayed;import java.util.concurrent.TimeUnit; public class RemovingElementsExample {    public static void main(String args[])    {        // Create a DelayQueue instance        DelayQueue<Delayed> queue = new DelayQueue<Delayed>();         // Create an object of type Delayed        Delayed ob = new Delayed() {            public long getDelay(TimeUnit unit)            {                return 24; // some value is returned            }             public int compareTo(Delayed o)            {                if (o.getDelay(TimeUnit.DAYS)                    > this.getDelay(TimeUnit.DAYS))                    return 1;                else if (o.getDelay(TimeUnit.DAYS)                         == this.getDelay(TimeUnit.DAYS))                    return 0;                return -1;            }        };         // Add the object to DelayQueue        queue.add(ob);         // Print initial size of Queue        System.out.println("Initial Size : " + queue.size());         // Remove the object ob from        // this DelayQueue        queue.remove(ob);         // Print the final size of the DelayQueue        System.out.println("Size after removing : " + queue.size());    }}
  
Initial Size : 1
Size after removing : 0
 
3. Accessing Elements
 
The peek() method of DelayQueue is used to retrieve the head of the DelayQueue, but does not remove it, as in the case of the poll() method where the head is removed from the DelayQueue.
 
Java
// Java Program Demonstrate accessing// elements of DelayQueue import java.util.concurrent.*;import java.util.*; // The DelayObject for DelayQueue// It must implement Delayed and// its getDelay() and compareTo() methodclass 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 Classpublic class AccessingElementsExample {    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));               // Print delayqueue        System.out.println("Original DelayQueue: " + DQ + "\n");               // removing all elements        DQ.clear();               // peek() method for returning head of the        // DelayQueue        System.out.println("Head of the DelayQueue: " + DQ.peek());    }}
  
Original DelayQueue: [
{ A, time=1600770273132}, 
{ B, time=1600770273134}]

Head of the DelayQueue: null
 
4. Traversing
 
The iterator() method of DelayQueue is used to return an iterator over all the elements in the DelayQueue.
 
Java
// Java Program Demonstrate iterating// over DelayQueue import java.util.concurrent.*;import java.util.*; // The DelayObject for DelayQueue// It must implement Delayed and// its getDelay() and compareTo() methodclass 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 Classpublic class IteratingExample {    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));         // Creating an iterator        Iterator val = DQ.iterator();         // print the value after iterating DelayQueue        System.out.println("The iterator values are: ");        while (val.hasNext()) {            System.out.println(val.next());        }    }}
  
The iterator values are: 

{ A, time=1600770415898}

{ B, time=1600770415900}

{ C, time=1600770415901}

{ D, time=1600770415902}
 
METHOD
DESCRIPTION
METHOD
DESCRIPTION
METHOD
DESCRIPTION
METHOD
DESCRIPTION
METHOD
DESCRIPTION
METHOD
DESCRIPTION
METHOD
DESCRIPTION
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/DelayQueue.html
 
Ganeshchowdharysadanala
arorakashish0911
Java-Collections
java-DelayQueue
Technical Scripter 2018
Java
Technical Scripter
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
Interfaces in Java
ArrayList in Java
Initialize an ArrayList in Java
Singleton Class in Java
Overriding in Java
Collections in Java
Set in Java
LinkedList in Java
Stream In Java