Java DelayQueue Example

By Arvind Rai, January 22, 2023
On this page, we will learn using DelayQueue class of java.util.concurrent package in our Java application.
1. The DelayQueue class is an unbounded blocking queue of delayed elements. The 'unbounded' means that queue has no fixed capacity and Integer.MAX_VALUE elements can be stored. The delayed element means that an element can only be taken from queue when its delay has expired.
2. Only that element will be at the head of the queue whose delay expired furthest in the past. If there is no such element whose delay is expired, then there will be no head in the queue and poll method will return null.
3. The DelayQueue accepts Delayed elements. The Delayed is an interface with getDelay(TimeUnit unit) method. The objects to be added in DelayQueue, has to implement Delayed interface. The expiration of element is considered when getDelay(TimeUnit.NANOSECONDS) method returns a value less than or equal to zero.
4. The unexpired element cannot be removed from queue using take or poll method. But other methods of DelayQueue, behave normally for the delayed elements, for example, size method returns the count of both expired and unexpired elements.
5. The DelayQueue implements Iterable, Collection, BlockingQueue and Queue interfaces.
6. We cannot add null elements in DelayQueue.
7. Find the DelayQueue class implementation from Java doc.
public class DelayQueue<E extends Delayed> 
        extends AbstractQueue<E> implements BlockingQueue<E> {
   ------
} 
We can see that The DelayQueue accepts the objects of Delayed type.

Delayed Interface

The Delayed interface is used to create classes that need to be acted upon only after a given delay. Find the Delayed interface declaration.
public interface Delayed extends Comparable<Delayed> {
   long getDelay(TimeUnit unit)
} 
The getDelay method returns the remaining delay associated with this object, in the given time unit.
The class implementing this interface must define a compareTo method that provides an ordering consistent with its getDelay method.

Creating Class with Delayed Interface

Find a class implementing Delayed interface. We need to implement compareTo and getDelay methods.
Example: Task.java
package com.concretepage;
import java.time.Duration;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class Task implements Delayed {
  private String name;
  private long timeToComplete = 0;

  Task(String name, long timeToComplete) {
	this.name = name;
	this.timeToComplete = timeToComplete + System.currentTimeMillis();
  }
  public String getName() {
    return name;
  }
  @Override
  public int compareTo(Delayed ob) {
	if (this.timeToComplete < ((Task)ob).timeToComplete) {
	  return -1;
	} else if (this.timeToComplete > ((Task)ob).timeToComplete) {
	  return 1;
	}
	return 0;
  }
  @Override
  public long getDelay(TimeUnit unit) {
	return unit.convert(Duration.ofMillis(timeToComplete - System.currentTimeMillis()));
  }
} 
We will use above class in our examples.

Constructors

Find the DelayQueue constructors.
1.
public DelayQueue() 
Creates a new DelayQueue.
2.
public DelayQueue(Collection<? extends E> c) 
Creates a DelayQueue initially containing the elements of the given collection. The elements of this collection must be of Delayed type.

Methods to store elements

1.
public boolean add(E e) 
Inserts the specified element into this delay queue.
2.
public boolean offer(E e) 
Inserts the specified element into this delay queue.
3.
public boolean offer(E e, long timeout, TimeUnit unit) 
Inserts the specified element into this delay queue. As the queue is unbounded, this method will never block.
4.
public void put(E e) 
Inserts the specified element into this delay queue. As the queue is unbounded this method will never block.

Methods to Fetch Elements

1.
public E peek() 
Retrieves, but does not remove, the head of this queue. If the queue is empty, it returns null otherwise this method always returns the element in such a way that if no expired element is there then the element that will expire next, will be returned.
2.
public E poll() 
Retrieves and removes the head of this queue, or returns null if this queue has no element with an expired delay.
3.
public E poll(long timeout, TimeUnit unit) throws InterruptedException 
Retrieves and removes the head of this queue, waiting if necessary until an element delay is expired or the given timeout is passed.
4.
public E take() throws InterruptedException 
Retrieves and removes the head of this queue, waiting if necessary until an element with an expired delay is available on this queue.

Example: AdddFetch.java
package com.concretepage;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.TimeUnit;
public class AdddFetch {
  public static void main(String... args) {
	DelayQueue<Task> dq = new DelayQueue<>();
	Task ob1 = new Task("X", 200);
	Task ob2 = new Task("Y", 100);
	Task ob3 = new Task("Z", 150);
	// add
	dq.add(ob1);
	dq.add(ob2);
	dq.add(ob3);

	try {
	// take
	  Task a = dq.take();
	  System.out.println(a.getName());
	} catch (InterruptedException e) {
	  e.printStackTrace();
	}
	// poll
	try {
	  Task b = dq.poll(250, TimeUnit.MILLISECONDS);
	  System.out.println(b.getName());
	} catch (InterruptedException e) {
	  e.printStackTrace();
	}
  }
} 
Output
Y
Z 

drainTo Method

1.
public int drainTo(Collection<? super E> c) 
Removes all available elements from this queue and adds them to the given collection.
2.
public int 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.

Other Methods

1.
public void clear() 
Atomically removes all of the elements from this delay queue.
2.
public Iterator<E> iterator() 
Returns an iterator over all the elements in this queue.
3.
public int remainingCapacity() 
Always returns Integer.MAX_VALUE because a DelayQueue is not capacity constrained.
4.
public boolean remove(Object o) 
Removes a single instance of the specified element from this queue, if it is present, whether or not it has expired.
5.
public int size() 
Returns the number of elements in this collection.
6.
public Object[] toArray() 
Returns an array containing all of the elements in this queue.
7.
public <T> T[] toArray(T[] a) 
Returns an array containing all of the elements in this queue.

Reference

Class DelayQueue
POSTED BY
ARVIND RAI
ARVIND RAI











©2023 concretepage.com | Privacy Policy | Contact Us