Thursday, May 15, 2008

Queue in Java


It’s an interface which extends the very famous Collection interface. Apparently, it is used for queuing up elements before processing. Since, it extends the Collection interface, so it automatically contains all the Collection operations. In addition, Queue provides operations for Insert/Extract/Inspect.

Queue is normally used to implement a Data Structure which requires a FIFO (First-In-First-Out) sequencing of elements. Queue normally does that only, but in few exceptional circumstances it behaves differently as well. For example, Priority Queues order elements according to a supplied comparator. Anyway, irrespective of the ordering the Head of the Queue will point to the element, which would be removed by a call to the remove method. FIFO queues allow insertion only at the tail of the queue to main the FIFO order, but other types of queues may follow a different element-placement policy.

Methods of the Queue interface:-

  • E peek() – it only retrieves, but doesn’t remove the head of the queue. Returns null if the queue is empty.
  • element() – it only retrieves the element without removing it. It’s similar to the peek method, the only difference is that it throws ‘NoSuchElementException’ if the queue is empty.
  • boolean offer(E o) – inserts the specified element, if possible. After a successful insertion, it returns true otherwise returns false. It’s similar to the Collection.add(E) method, but it gives better control on the insertion process. Collection.add(E) will only fail if it throws an unchecked exception, so ‘offer is preferable to add if you want to restrict the insertion of elements to the queue based on certain policies.
  • E poll() – this method retrieves and removes the head of the queue. It returns null if the queue is empty.
  • E remove() – same as the poll method. The only difference is that it throws ‘NoSuchElementException’ exception if the queue is empty.

Blocking Queue methods, which are very frequent in concurrent programming, aren’t defined by the Queue interface. We have another interface named BlockingQueue, which extends the Queue interface.

One important thing to notice about the insertion process of a Queue is that null elements are normally not allowed for insertion. We do have few exceptions to this rule as well. LinkedList, which implements Queue doesn’t refuse null elements to be inserted. But, it shouldn’t be used as null is used by the peek and poll methods to signify a different thing.



Share/Save/Bookmark


No comments: