简体   繁体   中英

LinkedBlockingQueue in java jdk 1.7

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM