1

I read LinkedBlockingQueue source code in JDK1.7 and can't understand the method.

public boolean offer(E e) {
    if (e == null) throw new NullPointerException();
    final AtomicInteger count = this.count;
    if (count.get() == capacity)
        return false;
    int c = -1;
    Node<E> node = new Node(e);
    final ReentrantLock putLock = this.putLock;
    putLock.lock();
    try {
        if (count.get() < capacity) {
            enqueue(node);
            c = count.getAndIncrement();
            if (c + 1 < capacity)
                notFull.signal();
        }
    } finally {
        putLock.unlock();
    }
    if (c == 0)
        signalNotEmpty();
    return c >= 0;
}

I don't know how this works.

 if (c == 0)
        signalNotEmpty();

if c == 0, means the queue is empty, so I think the method should be

signalEmpty();

Is there anyone could enlighten me? Thanks.

1 Answer 1

1

c is initialized with

c = count.getAndIncrement();

So its value if the size of the queue before inserting the new node. So if the size before inserting the new node was 0, signalNotEmpty() is called to signal that the queue went from empty to not empty.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.