Reputation: 319
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.
Upvotes: 1
Views: 109
Reputation: 691735
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.
Upvotes: 1