【问题标题】:What does "Aren't allocating the things put into queues" mean?“没有分配放入队列的东西”是什么意思?
【发布时间】:2021-12-08 00:46:20
【问题描述】:

我在读这个:

https://concurrency.markmail.org/search/?q=ArrayBlockingQueue+LinkedBlockingQueue#query:ArrayBlockingQueue%20LinkedBlockingQueue%20from%3A%22Doug%20Lea%22+page:1+mid:sgx3amdfga7esqul+state:results

Doug Lea 说:

通常,当您将某物放入队列时,您将拥有 刚刚分配了新的东西。同样,当你采取 一些你通常使用它然后让它变成垃圾的东西。在 在这种情况下,队列节点的额外分配不会产生 整体 GC 差异很大,所以你最好做得更好 LinkedBlockingQueue 的可扩展性。我认为这是最常见的 用例。

但是,如果您不分配放入队列中的东西,并且不要 当队列两者都不是时,预计会有很多线程竞争 空也不满,那么 ArrayBlockingQueue 可能会更好地工作。

我想知道Aren't allocating the things put into queues是什么意思?

另外,这句话:don't expect lots of threads to be contending when the queue is neither empty nor full, then ArrayBlockingQueue is likely to work better,有人能具体解释一下吗?

【问题讨论】:

  • 从上下文来看,这似乎意味着您放入队列中的东西是否长期存在,即很久以前有人已经分配了它们。

标签: java multithreading concurrency java.util.concurrent


【解决方案1】:

对我来说,这似乎意味着以下:

  1. 我想知道Aren't allocating the things put into queues 是什么意思?

    这是关于他们讨论的 GC 开销。

    LinkedBlockingQueue 为每个添加的项目创建 new internal Node object,这意味着它会生成垃圾并因此导致垃圾回收 (GC)。
    Doug 说,我们存储在队列中的项目通常是以下对象:

    • 在它们被添加到队列之前创建
    • 在它们从队列中移除后不久就变得未使用(并且有资格获得 GC)

    在这些情况下,项目本身会导致 GC,因此 Node 对象也需要 GC 不是问题。

    但是如果你只在队列中存储长生命周期的对象,那么LinkedBlockingQueue 可能会成为导致 GC 的唯一因素。
    那么你可能想使用ArrayBlockingQueue 来避免GC。
    ArrayBlockingQueue 在添加/删除项目时不会创建任何对象)

  2. 另外,这句话:don't expect lots of threads to be contending when the queue is neither empty nor full, then ArrayBlockingQueue is likely to work better,有人能具体解释一下吗?

    LinkedBlockingQueue uses two locks:一个用于put(),一个用于take()
    ArrayBlockingQueue uses one lock 用于put()take()
    结果当“the queue is neither empty nor full”(即put()take()都不需要等待时)并且有两个线程:一个执行put(),另一个执行take()

    • 如果队列是LinkedBlockingQueue,那么线程不会互相阻塞
    • 如果队列是ArrayBlockingQueue,那么一个线程将不得不等待另一个线程完成

【讨论】:

  • 说得好。可能让 OP 感到困惑的一件事是 Doug Lea 所指的长寿对象的类型。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-24
  • 2023-03-27
  • 2018-04-09
  • 1970-01-01
  • 2012-01-22
  • 2019-11-03
  • 2022-01-23
相关资源
最近更新 更多