Wednesday, May 2, 2018

Simple blocking queue in Java using wait and notify

Simple blocking queue in Java using wait and notify

package sample;

import java.util.LinkedList;
import java.util.List;

/**
 * A Queue Implementation
 * A Blocking Queue is a queue in which enQueue(insertion) and deQueue (removal) will wait and will be synchnronized.
 * This is used mostly in Producer/ Consumer problem where we generally use a ArrayBlockingQueue or LinkedBlockingQueue.
 *
 * @param <T>
 */

public class BlockingQueue<T> {
    private final List<T> queueList;   // Kept final
    private final int size;

    public BlockingQueue(int limit) {
        queueList = new LinkedList<T>();
        size = limit;
    }

    public synchronized void enqueue(T item) throws InterruptedException {
        while (size == queueList.size()) {  // if full waiting
            wait();
        }
        if (queueList.size() == 0) {   // if empty notifying others
            notifyAll();
        }
        queueList.add(item);     // adding the element
    }


    public synchronized T dequeue() throws InterruptedException {
        while (queueList.size() == 0) {  // If empty waiting...
            wait();
        }
        if (size == queueList.size()) {  // if full notifying others
            notifyAll();
        }
        return queueList.remove(0);   // Removing the element
    }
}

No comments:

Post a Comment

Categories