DelayQueue put() method in Java with Examples
Last Updated :
11 Aug, 2021
The put(E ele) method of DelayQueue class in Java is used to inserts a given element into the delay queue container. Hetre, E is the type of element maintained by this DelayQueue container.
Syntax:
public void put(E ele)
Parameters: This method accepts only one parameter ele. It is the element which will be inserted into the delay queue.
Return Value: The return type of the method is void and it does not return any value.
Exception:
- NullPointerException: It is thrown if the given value is null.
Below programs illustrate the put() method of DelayQueue in Java:
Program 1:
Java
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
public class GFG {
public static void main(String args[])
{
DelayQueue<Delayed> queue = new DelayQueue<Delayed>();
System.out.println( "Before calling put() : "
+ queue.isEmpty());
Delayed ele = new Delayed() {
public long getDelay(TimeUnit unit)
{
return 24 ;
}
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 ;
}
};
queue.put(ele);
System.out.println( "After calling put() : "
+ queue.isEmpty());
}
}
|
Output:
Before calling put() : true
After calling put() : false
Program 2 : Demonstration of NullPointerException.
Java
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
public class GFG {
public static void main(String args[])
{
DelayQueue<Delayed> queue = new DelayQueue<Delayed>();
try {
queue.put( null );
}
catch (Exception e) {
System.out.println(e);
}
}
}
|
Output:
java.lang.NullPointerException
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/DelayQueue.html#put(E)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...