Java Concurrency Utilities : Custom Implementation

Blocking Queue

Before implementing , one must know what BlockingQueue is : Java BlockingQueue interface in the java.util.concurrent package represents a queue which is thread safe to put into, and take instances from.  BlockingQueue is typically used to have on thread produce objects, which another thread consumes.

Implementation :
public class CustomBlockingQueue {

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

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


    public synchronized void enqueue(Object item)
            throws InterruptedException  {
        while(this.queue.size() == this.limit) {
            wait();
        }
        notifyAll();
        this.queue.add(item);
    }


    public synchronized Object dequeue()
            throws InterruptedException{
        while(this.queue.size() == 0){
            wait();
        }
        notifyAll();
        return this.queue.remove(0);
    }

}

Explanation :

To implement the blocking queue we have created a queue in which elements will  be added and taken out. We have created two enque and deque .In enque() method is used for producing and dequed for consuming. In enqueue method using the while() loop and condition we wait untill the queue is full and in the dequeu method we wait untill the queue is empty. Once any element is added in the queue, consumer thread consumer notify() to other thread.



Comments

Popular posts from this blog

Deploy standalone Spring MVC Application in Docker Container

Refactor Code : Separate Query from Modifier

HTTP : Must known Protocol (Part 1)