DelayQueue in Java


DelayQueue Java MultithreadingViews 1719

Java DelayQueue

DelayQueue is a class in Java that implements the BlockingQueue interface. This class is part of the Collections framework and is present in the java.util.concurrent package. The DelayQueue removes only those elements whose time has expired. This means we can remove an element only if it completes its waiting time or the delay expires. These elements have to implement the Delayed interface if it needs to be present in the DelayQueue. DelayQueue is a type of unbounded BlockingQueue. We can identify that the element has elapsed the delay when the getDelay() method returns 0 or a negative value.

A DelayQueue is also a special type of PriorityQueue that orders the elements in the queue based on the delay time. When there are no elements with a delay, then the poll() method returns null. This means that there is no head element to retrieve. We cannot store null values in a DelayQueue.

Hierarchy

DelayQueue in Java

Constructors in DelayQueue

Below are the constructors present in the DelayQueue class in Java.

ConstructorDescription
DelayQueue()Creates an empty DelayQueue
DelayQueue(Collection c)Creates a DelayQueue with the specified collection of elements

Methods in DelayQueue

Below are the methods present in the DelayQueue class. It also implements the methods in the Collection and Queue interfaces.

MethodDescription
boolean add(Element e)Adds a specified element into a DelayQueue
void clear()Clears the DelayQueue by removing all the elements in the queue
int drainTo(Collection c)Removes all the elements from the queue and moves it to the specified Collection
int drainTo(Collection c, int maxElements)Removes the maximum number of specified elements from the queue and moves it to the specified Collection
Delayed element()Retrieves but does not remove the head of the queue
Iterator iterator()Returns an iterator over the elements in the DelayQueue
boolean offer(Element e)Inserts the specified element into the DelayQueue
Delayed peek()Retrieves the head of the queue and does not remove it
Delayed poll()Retrieves and removes the head of the queue
void put(Element e)Inserts the specified element
int remainingCapacity()Returns the available capacity of the DelayQueue
Delayed remove()Removes the head element of the queue
boolean remove(Element e)Removes the specified element from the queue
int size()Returns the size of the DelayQueue
Delayed take()Retrieves and removes the head of the queue

DelayQueue Examples

Now we will see various examples of using the methods of DelayQueue class in Java

Example: Add elements

This example shows how to create a class that implements the Delayed interface and add elements to the DelayQueue using the add() method. Since we are implementing the Delayed interface, we need to override the compareTo() and getDelay() methods.

import java.util.concurrent.*;

public class DelayQueueDemo {

  public static void main(String[] args) {
    DelayQueue<DelayObj> dq = new DelayQueue<DelayObj>();
    dq.add(new DelayObj("Raju",32));
    dq.add(new DelayObj("Lokesh",45));
    dq.add(new DelayObj("Hari", 20));
    
    System.out.println("Elements in DelayQueue: " + dq);
    
    

  }

}

class DelayObj implements Delayed {
  
  private String name;
  private int age;
  private long time;
  
  DelayObj(String name, int age) {
    this.name = name;
    time = System.currentTimeMillis() + time;
    this.age = age;
  }
   
  @Override
  public int compareTo(Delayed o) {
    if (this.time < ((DelayObj)o).time) {
            return -1;
        }
        if (this.time > ((DelayObj)o).time) {
            return 1;
        }
        return 0;
  }
  
  public String toString() {
     return "\n{"
                + "name=" + name
                + ", age =" + age
                + "}";
  }

  @Override
  public long getDelay(TimeUnit unit) {
    long diff = time - System.currentTimeMillis();
    return unit.convert(diff,TimeUnit.MILLISECONDS);
  }
  
}
Elements in DelayQueue: [
{name=Raju, age =32}, 
{name=Lokesh, age =45}, 
{name=Hari, age =20}]

Example: Remove elements

Below is the example to remove elements using the remove(), poll() and take() methods of the DelayQueue class. All these methods remove the head element of the queue.

import java.util.concurrent.*;

public class DelayQueueDemo {

  public static void main(String[] args) throws InterruptedException {
    DelayQueue<DelayObj> dq = new DelayQueue<DelayObj>();
  
    dq.add(new DelayObj("Raju",32));
    dq.add(new DelayObj("Lokesh",45));
    dq.add(new DelayObj("Hari", 20));
    dq.add(new DelayObj("Vasu", 55));
    dq.add(new DelayObj("Karthik",15));
    
    System.out.println("Elements in DelayQueue: " + dq);
    
    System.out.println("Removing elements...");
    dq.remove();
    dq.take();
    dq.poll();
    
    System.out.println("Elements in DelayQueue after removing elements: " + dq);

  }

}

class DelayObj implements Delayed {
  
  private String name;
  private int age;
  private long time;
  
  DelayObj(String name, int age) {
    this.name = name;
    time = System.currentTimeMillis() + time;
    this.age = age;
  }
   
  @Override
  public int compareTo(Delayed o) {
    if (this.time < ((DelayObj)o).time) {
            return -1;
        }
        if (this.time > ((DelayObj)o).time) {
            return 1;
        }
        return 0;
  }
  
  public String toString() {
     return "\n{"
                + "name=" + name
                + ", age =" + age
                + "}";
  }

  @Override
  public long getDelay(TimeUnit unit) {
    long diff = time - System.currentTimeMillis();
    return unit.convert(diff,TimeUnit.MILLISECONDS);
  }
  
}
Elements in DelayQueue: [
{name=Raju, age =32}, 
{name=Lokesh, age =45}, 
{name=Hari, age =20}, 
{name=Vasu, age =55}, 
{name=Karthik, age =15}]
Removing elements...
Elements in DelayQueue after removing elements: [
{name=Hari, age =20}, 
{name=Lokesh, age =45}]

Example: Access elements

The below example shows how to access the head element using the element() and peek() methods of the Java DelayQueue class. The size() method returns the size of the DelayQueue.

import java.util.concurrent.*;

public class DelayQueueDemo {

  public static void main(String[] args) throws InterruptedException {
    DelayQueue<DelayObj> dq = new DelayQueue<DelayObj>();
  
    dq.add(new DelayObj("Raju",32));
    dq.add(new DelayObj("Lokesh",45));
    dq.add(new DelayObj("Hari", 20));
    dq.add(new DelayObj("Vasu", 55));
    dq.add(new DelayObj("Karthik",15));
    
    System.out.println("Elements in DelayQueue: " + dq);
    System.out.println("Head element using element method: " + dq.element());
    System.out.println("Head element using peek method: " + dq.peek());
    System.out.println("Size of the queue: " + dq.size());

  }

}

class DelayObj implements Delayed {
  
  private String name;
  private int age;
  private long time;
  
  DelayObj(String name, int age) {
    this.name = name;
    time = System.currentTimeMillis() + time;
    this.age = age;
  }
   
  @Override
  public int compareTo(Delayed o) {
    if (this.time < ((DelayObj)o).time) {
            return -1;
        }
        if (this.time > ((DelayObj)o).time) {
            return 1;
        }
        return 0;
  }
  
  public String toString() {
     return "\n{"
                + "name=" + name
                + ", age =" + age
                + "}";
  }

  @Override
  public long getDelay(TimeUnit unit) {
    long diff = time - System.currentTimeMillis();
    return unit.convert(diff,TimeUnit.MILLISECONDS);
  }
  
}
Elements in DelayQueue: [
{name=Raju, age =32}, 
{name=Lokesh, age =45}, 
{name=Hari, age =20}, 
{name=Vasu, age =55}, 
{name=Karthik, age =15}]
Head element using element method: 
{name=Raju, age =32}
Head element using peek method: 
{name=Raju, age =32}
Size of the queue: 5

Example: Iterate elements

We can iterate through all the elements in the DelayQueue using the iterator() method. To retrieve each element, we can use the next() method.

import java.util.Iterator;
import java.util.concurrent.*;

public class DelayQueueDemo {

  public static void main(String[] args) throws InterruptedException {
    DelayQueue<DelayObj> dq = new DelayQueue<DelayObj>();
  
    dq.add(new DelayObj("Raju",32));
    dq.add(new DelayObj("Lokesh",45));
    dq.add(new DelayObj("Hari", 20));
    dq.add(new DelayObj("Vasu", 55));
    dq.add(new DelayObj("Karthik",15));
    
    Iterator it = dq.iterator();
    while(it.hasNext())
      System.out.println(it.next());

  }

}

class DelayObj implements Delayed {
  
  private String name;
  private int age;
  private long time;
  
  DelayObj(String name, int age) {
    this.name = name;
    time = System.currentTimeMillis() + time;
    this.age = age;
  }
   
  @Override
  public int compareTo(Delayed o) {
    if (this.time < ((DelayObj)o).time) {
            return -1;
        }
        if (this.time > ((DelayObj)o).time) {
            return 1;
        }
        return 0;
  }
  
  public String toString() {
     return "\n{"
                + "name=" + name
                + ", age =" + age
                + "}";
  }

  @Override
  public long getDelay(TimeUnit unit) {
    long diff = time - System.currentTimeMillis();
    return unit.convert(diff,TimeUnit.MILLISECONDS);
  }
  
}
{name=Raju, age =32}

{name=Lokesh, age =45}

{name=Hari, age =20}

{name=Vasu, age =55}

{name=Karthik, age =15}

 

Reference

Translate ยป