Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java LinkedBlockingQueue Realization

I looked at JDK LinkedBlockingQueue class and was lost.

public void put(E e) throws InterruptedException {
    if (e == null) throw new NullPointerException();
    // Note: convention in all put/take/etc is to preset local var
    // holding count negative to indicate failure unless set.
    int c = -1;
    final ReentrantLock putLock = this.putLock;
    final AtomicInteger count = this.count;
    putLock.lockInterruptibly();
    try {
        /*
         * Note that count is used in wait guard even though it is
         * not protected by lock. This works because count can
         * only decrease at this point (all other puts are shut
         * out by lock), and we (or some other waiting put) are
         * signalled if it ever changes from
         * capacity. Similarly for all other uses of count in
         * other wait guards.
         */
        while (count.get() == capacity) { 
                notFull.await();
        }
        enqueue(e);
        c = count.getAndIncrement();
        if (c + 1 < capacity)
            notFull.signal();
    } finally {
        putLock.unlock();
    }
    if (c == 0)
        signalNotEmpty();
}

Look please at the last condition (c == 0), I think it should be (c != 0)

Thank you, I understand. But I have another one question about LinkedBlockingQueue realization. enqueue and dequeue function must not intersect. I see that when put() is executed, take() could be executed too. And head and tail objects have not synchronization, than enqueue and dequeue could work simultaneously in different thread. It is not thread-safe, failures could occur.

like image 737
itun Avatar asked Aug 08 '26 20:08

itun


1 Answers

No, the intent is to signal only when the queue goes from 0 to 1 (i.e. the first time something is added to an empty queue). you don't need to "signal not empty" when adding items to a queue which already has items in it. (You'll notice that the notEmpty condition is only waited on when the queue count == 0).

like image 76
jtahlborn Avatar answered Aug 11 '26 10:08

jtahlborn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!