Locking using ReentrantLock

I wrote my own BlockingQueue implementation for practice. I am trying to avoid using synchronized keyword for methods. I would like to use ReentrantLock instead.

What is the best way to write this implementation? I'm not a Java ninja and really appreciate if someone can spot the bugs in my code here and suggest better ways to implement it.

public class MyBlockingQueue<T> {

private Queue<T> queue;
private AtomicInteger limit = new AtomicInteger(10);
private Lock put_lock = new ReentrantLock();
private Lock take_lock = new ReentrantLock();
private Condition put_condition = put_lock.newCondition();
private Condition take_condition = take_lock.newCondition();

public MyBlockingQueue(AtomicInteger limit){
    queue = new LinkedList<T>();
    this.limit = limit;
}

public boolean put(T item) throws InterruptedException{
    put_lock.lockInterruptibly();
    try {
        while(queue.size() == limit.get()) {
            put_condition.await();
        }
        put_condition.signal();
        queue.add(item);
    } finally{
        put_lock.unlock();
    }

    return true;
}

public T take() throws InterruptedException{
    take_lock.lockInterruptibly();
    try {
        while (queue.size() == 0) {
            take_condition.await();
        }
        take_condition.signal();
        return queue.poll();
    } finally {
        take_lock.unlock();
    }
}

      

Thank you for your time!

+3


source to share


1 answer


You can compare your logic to jdk's open source implementation of the blocking queue.

ArrayBlockingQueue



Btw..ArrayBlockingQueue also uses ReentrantLock

+1


source







All Articles