Open In App

DelayQueue Class in Java with Example

Last Updated : 20 May, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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

DelayQueue Class in Java

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.

Constructors of DelayQueue

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() 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=" + 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 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);
    }
}


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

 

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() 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=" + 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());
    }
}


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

 

Basic Operations

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());
    }
}


 
 

Output

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());
    }
}


 
 

Output

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() 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 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());
    }
}


 
 

Output

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() 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 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());
        }
    }
}


 
 

Output

The iterator values are: 

{ A, time=1600770415898}

{ B, time=1600770415900}

{ C, time=1600770415901}

{ D, time=1600770415902}

 

Methods of DelayQueue

METHOD

DESCRIPTION

add​(E e) Inserts the specified element into this delay queue.
clear() Atomically removes all of the elements from this delay queue.
drainTo​(Collection<? super E> c) Removes all available elements from this queue and adds them to the given collection.
drainTo​(Collection<? super E> c, int maxElements) Removes at most the given number of available elements from this queue and adds them to the given collection.
iterator() Returns an iterator over all the elements (both expired and unexpired) in this queue.
offer​(E e) Inserts the specified element into this delay queue.
offer​(E e, long timeout, TimeUnit unit) Inserts the specified element into this delay queue.
peek() Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
poll() Retrieves and removes the head of this queue, or returns null if this queue has no elements with an expired delay.
poll​(long timeout, TimeUnit unit) 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.
put​(E e) Inserts the specified element into this delay queue.
remainingCapacity() Always returns Integer.MAX_VALUE because a DelayQueue is not capacity constrained.
remove​(Object o) Removes a single instance of the specified element from this queue, if it is present, whether or not it has expired.
take() Retrieves and removes the head of this queue, waiting if necessary until an element with an expired delay is available on this queue.
toArray() Returns an array containing all of the elements in this queue.
toArray​(T[] a) Returns an array containing all of the elements in this queue; the runtime type of the returned array is that of the specified array.

Methods declared in class java.util.AbstractQueue

METHOD

DESCRIPTION

addAll​(Collection<? extends E> c) Adds all of the elements in the specified collection to this queue.
element() Retrieves, but does not remove, the head of this queue.
remove() Retrieves and removes the head of this queue.

Methods declared in class java.util.AbstractCollection

METHOD

DESCRIPTION

contains​(Object o) Returns true if this collection contains the specified element.
containsAll​(Collection<?> c) Returns true if this collection contains all of the elements in the specified collection.
isEmpty() Returns true if this collection contains no elements.
removeAll​(Collection<?> c) Removes all of this collection’s elements that are also contained in the specified collection (optional operation).
retainAll​(Collection<?> c) Retains only the elements in this collection that are contained in the specified collection (optional operation).
toString() Returns a string representation of this collection.

Methods declared in interface java.util.concurrent.BlockingQueue

METHOD

DESCRIPTION

contains​(Object o) Returns true if this queue contains the specified element.

Methods declared in interface java.util.Collection

METHOD

DESCRIPTION

addAll​(Collection<? extends E> c) Adds all of the elements in the specified collection to this collection (optional operation).
containsAll​(Collection<?> c) Returns true if this collection contains all of the elements in the specified collection.
equals​(Object o) Compares the specified object with this collection for equality.
hashCode() Returns the hash code value for this collection.
isEmpty() Returns true if this collection contains no elements.
parallelStream() Returns a possibly parallel Stream with this collection as its source.
removeAll​(Collection<?> c) Removes all of this collection’s elements that are also contained in the specified collection (optional operation).
removeIf​(Predicate<? super E> filter) Removes all of the elements of this collection that satisfy the given predicate.
retainAll​(Collection<?> c) Retains only the elements in this collection that are contained in the specified collection (optional operation).
size() Returns the number of elements in this collection.
spliterator() Creates a Spliterator over the elements in this collection.
stream() Returns a sequential Stream with this collection as its source.
toArray​(IntFunction<T[]> generator) Returns an array containing all of the elements in this collection, using the provided generator function to allocate the returned array.

Methods declared in interface java.lang.Iterable

METHOD

DESCRIPTION

forEach​(Consumer<? super T> action) Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.

Methods declared in interface java.util.Queue

METHOD

DESCRIPTION

element() Retrieves, but does not remove, the head of this queue.
remove() Retrieves and removes the head of this queue.

Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/DelayQueue.html

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads