Java中的并发和阻塞队列 [英] Concurrent and Blocking Queue in Java

查看:150
本文介绍了Java中的并发和阻塞队列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个线程推送事件到第二个线程的入队列的经典问题。只有这一次,我对表演非常感兴趣。我想实现的是:




  • 我想同时访问队列,生产者推送,接收器poping。 b $ b
  • 当队列为空时,我将消费者阻止到队列,等待生产者。



我的第一个想法是使用LinkedBlockingQueue,但我很快意识到,它不是并发的性能受损。另一方面,我现在使用ConcurrentLinkedQueue,但我仍然支付每个出版物的wait()/ notify()的费用。因为消费者,在找到一个空队列,不阻塞,我必须同步和wait()锁。另一方面,生产者必须在每次发布时都获得锁和notify()。总的结果是,我在每一个出版物中支付
sycnhronized(lock){lock.notify()} 的成本,即使不需要。 / p>

我需要这里的猜测,是一个阻塞和并发的队列。我想象一个push()操作在ConcurrentLinkedQueue中工作,当一个额外的notify()对象的推动元素是列表中的第一个。这样的检查,我认为已经存在于ConcurrentLinkedQueue,因为推送需要连接下一个元素。因此,这将比每次在外部锁上同步更快。



这样的东西是否可用/合理?

解决方案

我认为你可以坚持 java.util.concurrent.LinkedBlockingQueue 不管你的怀疑。它是并发的。虽然,我不知道它的性能。可能,其他实现 BlockingQueue 将更适合你。他们没有太多,所以进行性能测试和测量。


I have the classic problem of a thread pushing events to the incoming queue of a second thread. Only this time, I am very interested about performance. What I want to achieve is:

  • I want concurrent access to the queue, the producer pushing, the receiver poping.
  • When the queue is empty, I wand the consumer to block to the queue, waiting for the producer.

My first idea was to use a LinkedBlockingQueue, but I soon realized that it is not concurrent and the performance suffered. On the other hand, I now use a ConcurrentLinkedQueue, but still I am paying the cost of wait()/notify() on each publication. Since the consumer, upon finding an empty queue, does not block, I have to synchronize and wait() on a lock. On the other part, the producer has to get that lock and notify() upon every single publication. The overall result is that I am paying the cost of sycnhronized (lock) {lock.notify()} in every single publication, even when not needed.

What I guess is needed here, is a queue that is both blocking and concurrent. I imagine a push() operation to work as in ConcurrentLinkedQueue, with an extra notify() to the object when the pushed element is the first in the list. Such a check I consider to already exist in the ConcurrentLinkedQueue, as pushing requires connecting with the next element. Thus, this would be much faster than synchronizing every time on the external lock.

Is something like this available/reasonable?

解决方案

I think you can stick to java.util.concurrent.LinkedBlockingQueue regardless of your doubts. It is concurrent. Though, I have no idea about its performance. Probably, other implementation of BlockingQueue will suit you better. There's not too many of them, so make performance tests and measure.

这篇关于Java中的并发和阻塞队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆