Blocking Queues in Java

Spread the love

Unlike List or a Set, can there be an data structure which is kind of blocking?

Yes those are blocking queues. Let’s see what is an Blocking queue.

A blocking queue is a queue which blocks a process or a thread if it tries to fetch something from the queue and the queue is empty

or

which blocks a process or a thread if it tries to add something to the queue and the queue is full.

Java 5 comes with blocking queue implementations in the java.util.concurrent package

public class BlockingQueue {

  private List queue = new LinkedList();
  private int  limit = 100;

  public BlockingQueue(int limit){
    this.limit = limit;
  }

  public synchronized void enqueue(Object item)
  throws InterruptedException  {
    while(this.queue.size() == this.limit) { \\line 2
      wait();
    }
    this.queue.add(item);\\line 4
    if(this.queue.size() == 1) {
      notifyAll(); \\line 6
    }
  }


  public synchronized Object dequeue()
  throws InterruptedException{
    while(this.queue.size() == 0){ \\line 2
      wait();
    }
    if(this.queue.size() == this.limit){ notifyAll();
    }

    return this.queue.remove(0); \\line 6
  }

}

If you see above, we have 2 methods which are enqueue(put) and dequeue(remove).

In dequeue method, it is synchronized and while calling the thread checks for the queue size. If it is zero, then it goes into wait state. If it is not zero, then it removes the element from the queue position 0 and returns.

Now consider If it goes into wait state, it will wait for any other thread to put an element into the queue so that size becomes greator than 1 and it can dequeue.

Now let’s check the enqueue method which does the job of putting elements into queue.

If size of the queue is full as checked in line 2, it goes into wait state. Else it puts the element in line 4 and notifies other threads in line 6 who are waiting like the one which we saw above.

Hope this was clear.

One more thing. The methods are synchronized so that only one thread can access the method at the moment. If it was not sync and instead of wait it was kind of sleep for 2 mins inside the while, then it may have been possible of two or multiple threads to simultaneously access the dequeue method and line 2 (size check) at the same time.

Once the element was available, All threads might try to remove the lement at the same time which can cause issues as null element would be fetched from the queue for 2 threads.

Hope this is clear as well.