DelayQueue class in Java with Example

DelayQueue class 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 poll will return null. DelayQueue accepts only those elements that belong to a class of type Delayed. DelayQueue implements the getDelay() method to return the remaining delay time.

Class Hierarchy:

java.lang.Object
  ↳ java.util.AbstractCollection<E>
    ↳ java.util.AbstractQueue<E>
      ↳ java.util.concurrent.DelayQueue<E>

Class Declaration:

public class DelayQueue<E extends Delayed>
  extends AbstractQueue<E>
    implements BlockingQueue<E>

Where E is the type of element maintained 
by this collection.

Constructors in Java DelayQueue:

  • DelayQueue(): This constructor is used to construct an empty DelayQueue.
  • DelayQueue(Collection<E> c): This constructor is used to construct a DelayQueue with the elements of the Collection passed as the parameter.

Below is a sample program to illustrate DelayQueue in Java:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program Demonstrate DelayQueue
  
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;
  
    // Contructor 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 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
        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 Dequee
        System.out.println("DelayQueue: "
                           + DQ);
  
        // create object of DelayQueue
        // using DelayQueue(Collection c) constructor
        BlockingQueue<DelayObject> DQ2
            = new DelayQueue<DelayObject>(DQ);
  
        // print Dequee
        System.out.println("DelayQueue: "
                           + DQ2);
    }
}

chevron_right


Output:

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}]

Methods of DelayQueue:

  1. add?(E e): This method inserts the specified element into this delay queue.
  2. clear?(): This method atomically removes all of the elements from this delay queue.
  3. drainTo?(Collection<E> c): This method removes all available elements from this queue and adds them to the given collection.
  4. drainTo?(Collection<E> c, int maxElements): This method removes at most the given number of available elements from this queue and adds them to the given collection.
  5. iterator?(): This method returns an iterator over all the elements (both expired and unexpired) in this queue.
  6. offer?(E e): This method Inserts the specified element into this delay queue.
  7. offer?(E e, long timeout, TimeUnit unit): This method Inserts the specified element into this delay queue.
  8. peek?(): This method retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
  9. poll?(): This method retrieves and removes the head of this queue, or returns null if this queue has no elements with an expired delay.
  10. poll?(long timeout, TimeUnit unit): This method retrieves and removes the head of this queue, waiting if necessary until an element with an expired delay is available on this queue, or the specified wait time expires.
  11. put?(E e): This method Inserts the specified element into this delay queue.
  12. remainingCapacity?(): This method always returns Integer.MAX_VALUE because a DelayQueue is not capacity constrained.
  13. remove?(Object o): This method removes a single instance of the specified element from this queue, if it is present, whether or not it has expired.
  14. size?(): This method returns the number of elements in this collection.
  15. take?(): This method retrieves and removes the head of this queue, waiting if necessary until an element with an expired delay is available on this queue.
  16. toArray?(): This method returns an array containing all of the elements in this queue.
  17. toArray?(T[] a): This method returns an array containing all of the elements in this queue; the runtime type of the returned array is that of the specified array.

Below is a sample program to illustrate DelayQueue methods in Java:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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() method
class DelayObject implements Delayed {
    private String name;
    private long time;
  
    // Contructor 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 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));
  
        // 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());
    }
}

chevron_right


Output:

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

Reference: https://docs.oracle.com/javase/9/docs/api/java/util/concurrent/DelayQueue.html



My Personal Notes arrow_drop_up

Strategy Path planning and Destination matters in success No need to worry about in between temporary failures

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.