Sunday, 22 January 2012

Queues in java

interface Queue was introduced with JDK 1.5 and is part of collections framework as Queue extends Collection interface. Queue stores elements in such way it returns the first one added. Queue follows the style of FIFO (first in, first out, remember stack follows LIFO, last in, first out). The first element in the queue is known as head and the last one is known as tail. New elements are added to the tail.
Following is the signature
public interface Queue extends Collection
As queue is a subclass of Collection, it can make use of all the methods of Collection and also the extra defined in its own such as inserting, retrieving and checking the elements.
Queue vs List
The major variation is that list allows retrieving the elements from any position. But, queue follows FIFO. LinkedList implements both interfaces List and Queue.
Programming Tip: Queue allows null elements. But do not add null as the return type of poll() method is also null when the queue is empty. The return null value may confuse (or conflict) with the actual null value you have added.
Realtime examples of Queue
  • Job Seekers Queue: Imagine a number of participants, aspiring job, appearing for interview. They stand in a queue. The first one stood (head) in the queue comes out first and attends the interview. The participant who comes late joins at the last of the queue (tail). While queue moves on a number check points may be there to check their bonafides and marks lists etc. Care must be taken one participant cannot be checked by many at a time or one checking person cannot check a number of participants at a time. For this a synchronized queue (java.util.concurrent.BlockingQueue) exactly suits.
  • Cinema Tickets Queue: A person who stands first in the booking counter leaves first.

No comments:

Post a Comment