首页 > 解决方案 > 为什么 Logback#AsyncAppender 使用 ArrayBlockingQueue 而不是 LinkedBlockingQueue

问题描述

logback 的异步 appender 使用BlockingQueue. 使用场景是multi-producer single-consumer并且需要绑定队列。所以两者都ArrayBlockingQueue应该LinkedBlockingQueue满足这种情况。

这是两个队列之间的区别。(来自对这两个队列之间差异的讨论。link1link2

LinkedBlockingQueue

  1. 应该有更好的吞吐量,因为它对头部和尾部使用单独的锁。

ArrayBlockingQueue

  1. 应该有更好的延迟,因为在数组中设置引用会更快。
  2. 预分配其支持数组。

我想知道使用ArrayBlockingQueue.

以下是 LogBack 源代码的一些片段(来自AsyncAppenderBase):

生产 :

// The default length of the queue is 256, which is configurable
private void put(E eventObject) {
        // If false (the default) the appender will block on appending to a full queue rather than losing the message. Set to true and the appender will just drop the message and will not block your application.
        if (neverBlock) {
            blockingQueue.offer(eventObject);
        } else {
            putUninterruptibly(eventObject);
        }
    }

消耗

while (parent.isStarted()) {
      try {
           E e = parent.blockingQueue.take();
               aai.appendLoopOnAppenders(e);
           } catch (InterruptedException ie) {
               break;
           }
      }
}

标签: javaconcurrencylogback

解决方案


推荐阅读