BlockingQueue 和 putAll

发布于 2024-09-07 18:15:28 字数 94 浏览 7 评论 0 原文

有谁知道为什么java的BlockingQueue没有putAll方法?这样的方法有问题吗?有什么好的方法可以解决这个问题而不必完全重新实现 BlockingQueue 吗?

Does anybody know why java's BlockingQueue does not have a putAll method? Is there a problem with such a method? Any good ways around this problem without having to completely re-implement BlockingQueue?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

意中人 2024-09-14 18:15:28
for (Item item : items) {
    queue.put(item);
}

3行,不确定这是否完全重新实现了阻塞队列。

我想它希望你一一放置,以防线程正在等待从中读取,它们不会等待你读完所有内容。

for (Item item : items) {
    queue.put(item);
}

3 lines, not sure thats totally re-implementing blocking queue.

I imagine it wants you to put 1 by 1 in case threads are waiting to read from it, they aren't waiting for you to finish reading them all.

马蹄踏│碎落叶 2024-09-14 18:15:28

我在 ArrayBlockingQueue 中发现了同样的问题。我们想要一些缺少的附加方法:

  • void putAll(Collection c)
    抛出 InterruptedException
  • intrainAtLeastOneTo(@OutputParam Collection c)
    抛出 InterruptedException
  • intrainAtLeastOneTo(@OutputParamCollectionc, int maxElements)
    抛出 InterruptedException

有些人主张使用 BlockingQueue>,但这需要 malloc 列表。有时你想避免它。另外,假设您希望生产者和消费者使用相同的“块”大小。

关于排出:同样,您可能希望生产者和消费者的块大小不匹配。因此,生产者可能会插入单个项目,但消费者会批量工作。 drainTo() 不会阻塞,因此 drainAtLeastOneTo() 是一个解决方案。

最后,我们复制了ArrayBlockingQueue的默认impl并直接添加方法。同样,一个缺点是您需要对具体类型进行操作,而不是接口 BlockingQueue

您还可以考虑使用著名的(臭名昭著的?)LMAX Disruptor,但该模型与标准 BlockingQueue 有很大不同,因为您无法控制项目何时被消耗。

I found the same issue with ArrayBlockingQueue. We wanted some additional methods that were missing:

  • void putAll(Collection<? extends E> c)
    throws InterruptedException
  • int drainAtLeastOneTo(@OutputParam Collection<? super E> c)
    throws InterruptedException
  • int drainAtLeastOneTo(@OutputParam Collection<? super E> c, int maxElements)
    throws InterruptedException

Some people advocate to use BlockingQueue<List<E>>, but that requires malloc'ing lists. Sometimes you want to avoid it. Also, that assumes you want producer and consumer to use the same "chunk" sizes.

Regarding draining: Again, you may want to have a mismatch between chunk size of producer and consumer. So producer might insert single items, but consumer works on batches. drainTo() does not block, so drainAtLeastOneTo() was a solution.

In the end, we copied the default impl of ArrayBlockingQueue and added the methods directly. Again, a drawback is that you need to operate on a concrete type, instead of interface BlockingQueue.

You may also consider using the famed (infamous?) LMAX Disruptor, but the model is quite different from a standard BlockingQueue, as you do not control when items are consumed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文