Java Program to Implement DelayQueue API

This Java program is to Implement DelayQueue API.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 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.

Here is the source code of the Java program to Implement DelayQueue API. The Java program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. import java.util.Collection;
  2. import java.util.Iterator;
  3. import java.util.concurrent.DelayQueue;
  4. import java.util.concurrent.Delayed;
  5. import java.util.concurrent.TimeUnit;
  6.  
  7. public class DelayQueueImpl<E extends Delayed>
  8. {
  9.     private DelayQueue<E> delayQueue;
  10.  
  11.     /** Creates a new DelayQueue that is initially empty. **/
  12.     public DelayQueueImpl()
  13.     {
  14.         delayQueue = new DelayQueue<E>();
  15.     }
  16.  
  17.     /**
  18.      * Creates a DelayQueue initially containing the elements of the given
  19.      * collection of Delayed instances.
  20.      **/
  21.     public DelayQueueImpl(Collection<? extends E> c)
  22.     {
  23.         delayQueue = new DelayQueue<>(c);
  24.     }
  25.  
  26.     /**
  27.      * Inserts the specified element into this delay queue.
  28.      **/
  29.     public boolean add(E e)
  30.     {
  31.         return delayQueue.add(e);
  32.     }
  33.  
  34.     /** Atomically removes all of the elements from this queue. **/
  35.     public void clear()
  36.     {
  37.         delayQueue.clear();
  38.     }
  39.  
  40.     /** Returns true if this queue contains the specified element. **/
  41.     public boolean contains(Object o)
  42.     {
  43.         return delayQueue.contains(o);
  44.     }
  45.  
  46.     /**
  47.      * Removes all available elements from this queue and adds them to the given
  48.      * collection.
  49.      **/
  50.     public int drainTo(Collection<? super E> c)
  51.     {
  52.         return delayQueue.drainTo(c);
  53.     }
  54.  
  55.     /**
  56.      * Removes at most the given number of available elements from this queue
  57.      * and adds them to the given collection.
  58.      **/
  59.     public int drainTo(Collection<? super E> c, int maxElements)
  60.     {
  61.         return delayQueue.drainTo(c, maxElements);
  62.     }
  63.  
  64.     /** Returns an iterator over the elements in this queue in proper sequence. **/
  65.     public Iterator<E> iterator()
  66.     {
  67.         return delayQueue.iterator();
  68.     }
  69.  
  70.     /**
  71.      * Inserts the specified element at the tail of this queue if it is possible
  72.      * to do so immediately without exceeding the queue's capacity, returning
  73.      * true upon success and false if this queue is full.
  74.      **/
  75.     public boolean offer(E e)
  76.     {
  77.         return delayQueue.offer(e);
  78.     }
  79.  
  80.     /** Inserts the specified element into this delay queue. **/
  81.     public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException
  82.     {
  83.         return delayQueue.offer(e, timeout, unit);
  84.     }
  85.  
  86.     /**
  87.      * Retrieves, but does not remove, the head of this queue, or returns null
  88.      * if this queue is empty.
  89.      **/
  90.     public E peek()
  91.     {
  92.         return delayQueue.peek();
  93.     }
  94.  
  95.     /**
  96.      * Retrieves and removes the head of this queue, or returns null if this
  97.      * queue is empty.
  98.      **/
  99.     public E poll()
  100.     {
  101.         return delayQueue.poll();
  102.     }
  103.  
  104.     /**
  105.      * Retrieves and removes the head of this queue, waiting if necessary until
  106.      * an element with an expired delay is available on this queue, or the
  107.      * specified wait time expires
  108.      **/
  109.     public E poll(long timeout, TimeUnit unit) throws InterruptedException
  110.     {
  111.         return delayQueue.poll(timeout, unit);
  112.     }
  113.  
  114.     /** Inserts the specified element into this delay queue. **/
  115.     public void put(E e) throws InterruptedException
  116.     {
  117.         delayQueue.put(e);
  118.     }
  119.  
  120.     /**
  121.      * Always returns Integer.MAX_VALUE because a DelayQueue is not capacity
  122.      * constrained.
  123.      **/
  124.     public int remainingCapacity()
  125.     {
  126.         return delayQueue.remainingCapacity();
  127.     }
  128.  
  129.     /**
  130.      * Removes a single instance of the specified element from this queue, if it
  131.      * is present, whether or not it has expired.
  132.      **/
  133.     public boolean remove(Object o) 
  134.     {
  135.         return delayQueue.remove(o);
  136.     }
  137.  
  138.     /** Returns the number of elements in this queue. **/
  139.     public int size()
  140.     {
  141.         return delayQueue.size();
  142.     }
  143.  
  144.     /**
  145.      * Retrieves and removes the head of this queue, waiting if necessary until
  146.      * an element with an expired delay is available on this queue.
  147.      **/
  148.     public E take() throws InterruptedException
  149.     {
  150.         return delayQueue.take();
  151.     }
  152.  
  153.     /**
  154.      * Returns an array containing all of the elements in this queue, in proper
  155.      * sequence.
  156.      **/
  157.     public Object[] toArray()
  158.     {
  159.         return delayQueue.toArray();
  160.     }
  161.  
  162.     /**
  163.      * Returns an array containing all of the elements in this queue; the
  164.      * runtime type of the returned array is that of the specified array.
  165.      **/
  166.     public <T> T[] toArray(T[] a)
  167.     {
  168.         return delayQueue.toArray(a);
  169.     }
  170.  
  171.     static class DelayObjects implements Delayed
  172.     {
  173.         public long time;
  174.  
  175.         public DelayObjects()
  176.         {
  177.             getDelay(TimeUnit.MILLISECONDS);
  178.         }
  179.  
  180.         @Override
  181.         public int compareTo(Delayed o)
  182.         {
  183.             if (this.time < ((DelayObjects) o).time)
  184.                 return -1;
  185.             else if (this.time > ((DelayObjects) o).time)
  186.                 return 1;
  187.             return 0;
  188.         }
  189.  
  190.         @Override
  191.         public long getDelay(TimeUnit unit)
  192.         {
  193.             time = System.currentTimeMillis();
  194.             return time;
  195.         }
  196.     }
  197.  
  198.     public static void main(String... arg) throws InterruptedException
  199.     {
  200.         DelayQueueImpl<DelayObjects> arrayBlockingQueue = new DelayQueueImpl<DelayObjects>();
  201.         DelayObjects delayObject1 = new DelayObjects();
  202.         Thread.sleep(100);
  203.         DelayObjects delayObject2 = new DelayObjects();
  204.         Thread.sleep(100);
  205.         DelayObjects delayObject3 = new DelayObjects();
  206.         Thread.sleep(100);
  207.         DelayObjects delayObject4 = new DelayObjects();
  208.         Thread.sleep(100);
  209.         DelayObjects delayObject5 = new DelayObjects();
  210.         try
  211.         {
  212.             arrayBlockingQueue.put(delayObject1);
  213.             arrayBlockingQueue.put(delayObject2);
  214.             arrayBlockingQueue.put(delayObject3);
  215.         } catch (InterruptedException e)
  216.         {
  217.             e.printStackTrace();
  218.         }
  219.         arrayBlockingQueue.add(delayObject4);
  220.         arrayBlockingQueue.add(delayObject5);
  221.         System.out.println("the delaytimes of the DelayQueue is ");
  222.         Iterator<DelayObjects> itr = arrayBlockingQueue.iterator();
  223.         while (itr.hasNext())
  224.         {
  225.             System.out.print(itr.next().time + "\t");
  226.         }
  227.         System.out.println();
  228.         arrayBlockingQueue.offer(new DelayObjects());
  229.         arrayBlockingQueue.offer(new DelayObjects());
  230.         System.out.println("the element time of the DelayQueue is(by peeking) "
  231.             + arrayBlockingQueue.peek().time);
  232.         System.out.println("the remaining capcity is "
  233.             + arrayBlockingQueue.remainingCapacity());
  234.         System.out.println("delayObject1 removed "
  235.             + arrayBlockingQueue.remove(delayObject1));
  236.         System.out.println("the DelayQueue contains delayObject2 :"
  237.             + arrayBlockingQueue.contains(delayObject2));
  238.         System.out.println("the hash DelayQueue contains delayObject3 :"
  239.             + arrayBlockingQueue.contains(delayObject3));
  240.         System.out.println("the size of the arrayblocingqueue is "
  241.             + arrayBlockingQueue.size());
  242.     }
  243. }

$ javac DelayQueueImpl.java
$ java DelayQueueImpl
the delaytimes of the DelayQueue is 
1385305755882	1385305755982	1385305756082	1385305756182	1385305756282	
the element time of the DelayQueue is(by peeking) 1385305755882
the remaining capcity is 2147483647
delayObject1 removed true
the DelayQueue contains delayObject2 :true
the DelayQueue contains delayObject3 :true
the size of the DelayQueue is 6

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement
advertisement
If you wish to look at all Java Programming examples, go to Java Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.