R@M3$H.NBlog

Circular Thread Safe Queue

20 January, 2014 - 6 min read

Implement a circular queue of integers of user-specified size using a simple array. Provide routines to initialize(), enqueue() and dequeue() the queue. Make it thread safe.

   1: public class CircularQueue {

   2:     private int[] data;

   3:     private int front;

   4:     private int rear;

   5:     private int size;

   6:     private int count;

   7:

   8:     public CircularQueue(int capacity) {

   9:         intialize(capacity);

  10:     }

  11:

  12:     public synchronized void intialize(int capacity) {

  13:         size = capacity;

  14:         data = new int[size];

  15:         front = 0;

  16:         rear = -1;

  17:         count = 0;

  18:     }

  19:

  20:     public synchronized void enqueue(int value) throws Exception {

  21:         if (count >= size) {

  22:             throw new Exception("Queue overflow");

  23:         }

  24:

  25:         if (rear == size - 1) {

  26:             rear = -1;

  27:         }

  28:

  29:         data[++rear] = value;

  30:         count++;

  31:     }

  32:

  33:     public synchronized void dequeue() throws Exception {

  34:         if (count <= 0) {

  35:             throw new Exception("Queue is Empty");

  36:         }

  37:

  38:         if (front == size - 1) {

  39:             front = 0;

  40:         } else if (front == rear) {

  41:             front = 0;

  42:             rear = -1;

  43:         } else {

  44:             front++;

  45:         }

  46:         count--;

  47:     }

  48:

  49:     /**

  50:      * For testing purpose only - Prints the values in the Queue

  51:      */

  52:     public void printQueue() {

  53:         if (front <= rear) {

  54:             for (int i = front; i <= rear; i++) {

  55:                 System.out.print(data[i] + " -> ");

  56:             }

  57:         } else if (count > 0) {

  58:             for (int i = front; i < size; i++) {

  59:                 System.out.print(data[i] + " -> ");

  60:             }

  61:             for (int i = 0; i <= rear; i++) {

  62:                 System.out.print(data[i] + " -> ");

  63:             }

  64:         }

  65:         System.out.println();

  66:     }

  67:

  68:     public static void main(String[] args) throws Exception {

  69:         CircularQueue cq = new CircularQueue(5);

  70:         cq.enqueue(1);

  71:         cq.enqueue(2);

  72:         cq.enqueue(3);

  73:         cq.enqueue(4);

  74:         cq.printQueue();

  75:

  76:         cq.dequeue();

  77:         cq.enqueue(5);

  78:         cq.enqueue(6);

  79:         cq.printQueue();

  80:     }

  81: }

  82:

  83: Output:

  84: 1 -> 2 -> 3 -> 4 ->

  85: 2 -> 3 -> 4 -> 5 -> 6 ->