简体   繁体   English

我的LinkedBlockingQueue实现是否需要同步?

[英]Does my implementation of LinkedBlockingQueue need to be synchronized?

To begin with, I have used search and found n topics related to this question. 首先,我使用了搜索并找到了与此问题相关的n个主题。 Unfortunately, they didin't help me, so it'll be n++ topics :) 不幸的是,他们没有帮助我,所以它将是n ++主题:)

Situation: I will have few working threads (the same class, just many dublicates) (let's call them WT) and one result writing thread (RT). 情况:我将有很少的工作线程(同一个类,只有很多dublicates)(让我们称之为WT)和一个结果写线程(RT)。

WT will add objects to the Queue, and RT will take them. WT会将对象添加到队列中,RT会接受它们。 Since there will be many WT won't there be any memory problems(independant from the max queue size)? 既然会有很多WT不存在任何内存问题(与最大队列大小无关)? Will those operations wait for each other to be completed? 这些操作会等待彼此完成吗?

Moreover, as I understand, BlockingQueue is quite slow, so maybe I should leave it and use normal Queue while in synchronized blocks? 而且,据我所知,BlockingQueue非常慢,所以也许我应该保留它并在同步块中使用正常的队列? Or should I consider my self by using SynchronizedQueue? 或者我应该通过使用SynchronizedQueue来考虑自己?

LinkedBlockingQueue is designed to handle multiple threads writing to the same queue. LinkedBlockingQueue旨在处理写入同一队列的多个线程。 From the documentation : 文档

BlockingQueue implementations are thread-safe. BlockingQueue实现是线程安全的。 All queuing methods achieve their effects atomically using internal locks or other forms of concurrency control. 所有排队方法都使用内部锁或其他形式的并发控制以原子方式实现其效果。 However, the bulk Collection operations addAll , containsAll , retainAll and removeAll are not necessarily performed atomically unless specified otherwise in an implementation. 但是,除非在实现中另有说明,否则批量Collection操作addAllcontainsAllretainAllremoveAll不一定以原子方式执行。

Therefore, you are quite safe (unless you expect the bulk operations to be atomic). 因此,您非常安全(除非您希望批量操作是原子操作)。

Of course, if thread A and thread B are writing to the same queue, the order of A's items relative to B's items will be indeterminate unless you synchronize A and B. 当然,如果线程A和线程B写入同一队列,除非您同步A和B,否则A项的相对于B项的顺序将是不确定的。

As to the choice of queue implementation, go with the simplest that does the job, and then profile. 至于队列实现的选择,请选择最简单的工作,然后进行配置。 This will give you accurate data on where the bottlenecks are so you won't have to guess. 这将为您提供有关瓶颈所在位置的准确数据,因此您无需猜测。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM