Java Program to Implement DelayQueue API
Last Updated :
21 Nov, 2022
The DelayQueue class belongs to java.util.concurrent package. DelayQueue implements the BlockingQueue interface. DelayQueue is a specialized Priority Queue that orders elements supported 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 within the least time.
An unbounded blocking queue of Delayed elements, in which an element can only be taken when its delay has expired. The head of the queue is that Delayed element whose delay expired furthest in the past. If no delay has expired there is no head and the poll will return null. Expiration occurs when an element's getDelay(TimeUnit.NANOSECONDS) method returns a value less than or equal to zero. Even though unexpired elements cannot be removed using take or poll, they are otherwise treated as normal elements. For example, the size method returns the count of both expired and unexpired elements. This queue does not permit null elements.
Procedure:
- Create a new DelayQueue that is initially empty. The DelayQueue class provides two constructors, one with no argument and one takes elements from another collection:
DelayQueue()
DelayQueue(Collection<? extends E> c)
- Create a DelayQueue initially containing the elements of the given collection of Delayed instances.
- Now, insert all the specified element into this delay queue using class "boolean add(E e)”.
- Retrieve and Remove an element from the DelayQueue.
Implementation:
- Step 1: Create a new DelayQueue that is initially empty.
- Step 2: Creates a DelayQueue initially containing elements of a collection of delayed instances.
- Step 3: Inserts the specified element into this delay queue.
- Step 4: Removes all available elements from this queue and adds them to the given collection.
- Step 5: Removes at most the given number of available elements from the queue and adds them to the given collection.
- Step 6: Inserts the specified element at the tail of this queue if possible to do so immediately without exceeding the queue's capacity.
- Step 7: Inserts the specified element into the delay queue.
- Step 8: Retrieve but do not remove the head of this queue or simply returns null if this queue is empty.
- Step 8(a): Retrieves and removes the head of this queue or simply returns null if this queue is empty.
- Step 8(b): Retrieves and removes the head of the queue waiting if necessary until an element with an expired delay is available on this queue.
- Step 9: Insert the specified element into the delay queue.
- Step 10: Removes a single instance of the specified element from this queue, if it is present.
- Step 11: Retrieves and removes the head of this queue, waiting if necessary until an element with an expired delay is available on this queue.
Example:
Java
// Java Program to implement DelayQueue API
// Importing classes from
// java.util package
import java.util.Collection;
import java.util.Iterator;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
// Class
public class DelayQueueImpl<E extends Delayed> {
private DelayQueue<E> delayQueue;
// Method 1
public DelayQueueImpl()
{
// Step 1: Create a new DelayQueue
// that is initially empty
delayQueue = new DelayQueue<E>();
}
// Method 2 - Creating delayQueue
// for containing elements
public DelayQueueImpl(Collection<? extends E> c)
{
// Step 2: Creates a DelayQueue initially containing
// elements of collection of Delayed instances
delayQueue = new DelayQueue<>(c);
}
// Method 3
// Step 3: Inserts the specified element
// into this delay queue
public boolean add(E e) { return delayQueue.add(e); }
// Method 4
public void clear()
{
// Automatically removes all of the elements
// from this queue
delayQueue.clear();
}
// Method 5
public boolean contains(Object o)
{
// Returns true if this queue contains the specified
// element else return false
return delayQueue.contains(o);
}
// Method 6
public int drainTo(Collection<? super E> c)
{
// Step 4: Removes all available elements from this
// queue and adds them to the given collection.
return delayQueue.drainTo(c);
}
// Method 7
// Step 5: Removes at most the given number of available
// elements from queue and adds them to the given
// collection
public int drainTo(Collection<? super E> c,
int maxElements)
{
return delayQueue.drainTo(c, maxElements);
}
// Method 8
public Iterator<E> iterator()
{
// Returns an iterator over the elements
// in this queue in proper sequence
return delayQueue.iterator();
}
// Method 9
// Step 6: Inserts the specified element at the tail of
// this queue if possible to do so immediately without
// exceeding the queue's capacity
// Method 10
public boolean offer(E e)
{
// Return true upon success and false
// if this queue is full else return false
return delayQueue.offer(e);
}
// Step 7: Inserts the specified element into delay
// queue
public boolean offer(E e, long timeout, TimeUnit unit)
throws InterruptedException
{
return delayQueue.offer(e, timeout, unit);
}
// Method 11
// Step 8: Retrieve but does not remove the head
// of this queue
public E peek()
{
// Or simply returns null if this queue is empty
return delayQueue.peek();
}
// Step 8(a): Retrieves and removes the head of this
// queue
public E poll()
{
// Or simply returns null if this queue is empty.
return delayQueue.poll();
}
// Step 8(b): Retrieves and removes the head of queue
// waiting if necessary untilan element with an
// expired delay is available on this queue
public E poll(long timeout, TimeUnit unit)
throws InterruptedException
{
return delayQueue.poll(timeout, unit);
}
// Method 12
// Step 9: Insert the specified element into delay queue
public void put(E e) throws InterruptedException
{
delayQueue.put(e);
}
// Method 13
public int remainingCapacity()
{
// Remember : Always returns Integer.MAX_VALUE
// because a DelayQueue is not capacity constrained
return delayQueue.remainingCapacity();
}
// Step 10: Removes a single instance of the specified
// element from this queue, if it is present
public boolean remove(Object o)
{
return delayQueue.remove(o);
}
public int size() {
return delayQueue.size();
}
// Retrieves and removes the head of this queue, waiting
// if necessary until an element with an expired delay
// is available on this queue.
public E take() throws InterruptedException
{
// Returns an array containing all of the elements
// in
// this queue, in proper sequence.
return delayQueue.take();
}
public Object[] toArray()
{
// Returns an array containing all elements in queue
return delayQueue.toArray();
}
// The runtime type of the returned array is
// that of the specified array
public <T> T[] toArray(T[] a)
{
return delayQueue.toArray(a);
}
// Class
static class DelayObjects implements Delayed {
// Member variable of class
public long time;
// Member function of class
public DelayObjects()
{
getDelay(TimeUnit.MILLISECONDS);
}
// Overriding using compareTo() method
@Override public int compareTo(Delayed o)
{
if (this.time < ((DelayObjects)o).time)
return -1;
else if (this.time > ((DelayObjects)o).time)
return 1;
return 0;
}
@Override public long getDelay(TimeUnit unit)
{
time = System.currentTimeMillis();
return time;
}
}
// Main driver method
public static void main(String[] args)
throws InterruptedException
{
// Creating object of class- DelayQueueImpl
DelayQueueImpl<DelayObjects> arrayBlockingQueue
= new DelayQueueImpl<DelayObjects>();
// Adding custom inputs
DelayObjects delayObject1 = new DelayObjects();
Thread.sleep(100);
DelayObjects delayObject2 = new DelayObjects();
Thread.sleep(100);
DelayObjects delayObject3 = new DelayObjects();
Thread.sleep(100);
DelayObjects delayObject4 = new DelayObjects();
Thread.sleep(100);
DelayObjects delayObject5 = new DelayObjects();
// Try block to check exceptions
try {
arrayBlockingQueue.put(delayObject1);
arrayBlockingQueue.put(delayObject2);
arrayBlockingQueue.put(delayObject3);
}
// Catch block to handle exceptions if occurs
catch (InterruptedException e) {
// Print the line number where exception occurred
e.printStackTrace();
}
// Adding objects to above queue
arrayBlockingQueue.add(delayObject4);
arrayBlockingQueue.add(delayObject5);
// Display message
System.out.print(
"Delaytimes of the DelayQueue is : ");
// iterator to traverse over collection
Iterator<DelayObjects> itr
= arrayBlockingQueue.iterator();
// Condition check using hasNext()
while (itr.hasNext()) {
// Print elements
System.out.print(itr.next().time + "\t");
}
// New line
System.out.println();
// Using offer() method over objects
arrayBlockingQueue.offer(new DelayObjects());
arrayBlockingQueue.offer(new DelayObjects());
// Print and Display messages to showcase
// implementation of DelayQueue API
System.out.println(
"Element time of the DelayQueue by peeking : "
+ arrayBlockingQueue.peek().time);
System.out.println(
"Remaining capacity : "
+ arrayBlockingQueue.remainingCapacity());
System.out.println(
"DelayObject1 removed ? : "
+ arrayBlockingQueue.remove(delayObject1));
System.out.println(
"DelayQueue contains DelayObject2 ? : "
+ arrayBlockingQueue.contains(delayObject2));
System.out.println(
"hash DelayQueue contains DelayObject3 ? : "
+ arrayBlockingQueue.contains(delayObject3));
System.out.println(
"Size of the ArrayBlocingQueue : "
+ arrayBlockingQueue.size());
}
}
OutputDelaytimes of the DelayQueue is : 1626870778483 1626870778583 1626870778683 1626870778786 1626870778886
Element time of the DelayQueue by peeking : 1626870778483
Remaining capacity : 2147483647
DelayObject1 removed ? : true
DelayQueue contains DelayObject2 ? : true
hash DelayQueue contains DelayObject3 ? : true
Size of the ArrayBlocingQueue : 6
Similar Reads
Java Program to Implement ArrayBlockingQueue API ArrayBlockingQueue class is a member of the Java Collection framework. ArrayBlockingQueue is a bounded blocking queue. The term bounded, means that the size of the Queue is fixed and cannot be changed. Any attempt to put element/elements into a full queue will lead to blocking operation. Similarly,
7 min read
Java Program to Implement ConcurrentLinkedQueue API The ConcurrentLinkedQueue class in Java is a part of the Java Collection Framework. It belongs to java.util.concurrent package. It was introduced in JDK 1.5. It is used to implement Queue with the help of LinkedList concurrently. It is an unbounded thread-safe implementation of Queue which inserts e
4 min read
Java Program to Implement PriorityQueue API A PriorityQueue is a linear data structure in which the elements are ordered according to their natural ordering or by some custom comparator provided at the queue at construction time. In PriorityQueue, the front of the queue points to the least element, and the rear points to the greatest element
4 min read
Java Program to Implement SynchronousQueue API SynchronousQueue is a special blocking queue with no internal capacity. It helps in exchange data or information between threads in a thread-safe manner. SynchronousQueue has only 2 supported operations: Both of these are blocking method which means when we want to add a piece of information or data
3 min read
Java Program to Implement LinkedTransferQueue API LinkedTransferQueue is a queue that orders elements FIFO (first-in-first-out) with respect to any given producer. The head of the queue is that element that has been on the queue the longest time for some producer. The tail of the queue is that element that has been on the queue the shortest time fo
5 min read
Java Program to Implement LinkedBlockingQueue API LinkedBlockingQueue API is an optionally-bounded queue based on linked nodes. It orders the elements in FIFO(First In First Out) order. The head of this queue is the element that has been there in the queue for the longest time and the tail of the queue is the element that has been in the queue for
6 min read
Java Program to Implement PriorityBlockingQueue API PriorityBlockingQueue is an unbounded blocking queue that uses the same ordering rules as class PriorityQueue and supplies blocking retrieval operations. The âblockingâ part of the name is added to imply the thread will block waiting until thereâs an item available on the queue. This class does not
2 min read
Java Threading Programs - Basic to Advanced Java threading is the concept of using multiple threads to execute different tasks in a Java program. A thread is a lightweight sub-process that runs within a process and shares the same memory space and resources. Threads can improve the performance and responsiveness of a program by allowing paral
3 min read
How to Implement a FIFO (First-In-First-Out) Queue in Java? FIFO stands for First In, First Out, which is a common way of organizing and manipulating Data Structure. In FIFO, the first element that is added to the data structure is the same first element that is to be removed first. Queue is a FIFO-based Data Structure. Here, the insert operation is called E
3 min read
Producer Consumer Solution using BlockingQueue in Java Thread The Producer-Consumer problem is a synchronization issue that arises when one or more threads generate data, placing it on a buffer, and simultaneously, one or more threads consume data from the same buffer. Doing so can cause a race condition in which the threads are racing against each other to c
6 min read