Java LinkedBlockingQueue 源代码困惑

标签 java blockingqueue

我正在阅读 Java LinkedBlockingQueue源代码,我有两个关于 put operation的问题.

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;
    Node<E> node = new Node<E>(e);
    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(node);
        c = count.getAndIncrement();
        if (c + 1 < capacity)
            notFull.signal();
    } finally {
        putLock.unlock();
    }
    if (c == 0)
        signalNotEmpty();
}

我不明白:

  1. 它检查c + 1 < capacity ,当它发出 notFull.signal() 时。为什么不使用 c < capacity
  2. 为什么会发出 signalNotEmptyc == 0在函数结束时?

此外,我也不明白为什么头/尾需要是 transient

最佳答案

您的两个问题的答案:

  1. c + 1 < capacity之前检查一下,有一个电话 c = count.getAndIncrement(); 。由于计数在检索并分配给 c 之后递增。 , c 之间存在 1 差异和实际计数,因此 + 1在支票上。
  2. 只有当队列从空转变为非空时才需要发送非空信号。仅当第一个元素添加到空(0 个元素)队列时才会出现这种情况。至于c此时是0而不是1,请引用第一个问题的答案。

关于headtailtransient :它们不需要在对象序列化时持久化,因为它们是在对象反序列化时通过默认构造函数初始化的。

关于Java LinkedBlockingQueue 源代码困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26772311/

相关文章:

java - 该代码原本应该反转第一个参数给出的字符串,但是它存在编译错误

java - 为什么我的 Java Calendar.setTime() 偶尔会设置错误的时间?

java - 将使用多线程的程序变成使用阻塞队列的程序

Java - LinkedBlockingQueue问题

java - 一个线程中的值不为 null,而另一线程中的值为 null

android - 带有队列与处理程序/Looper的Android线程: which one is efficient?

java - 使用 SynchronousQueue 解决消费者生产者并发问题。公平属性不起作用

java - 从带注释的字段接收注释值

java - 随机长,能不能连续两次是同一个数

java - 单击搜索按钮后 JList 不填充