Java LinkedBlockingQueue put vs offer
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19419805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
LinkedBlockingQueue put vs offer
提问by Scientist
I have a linked blocking queue in which I am performing insertion and removal operations.
我有一个链接的阻塞队列,我在其中执行插入和删除操作。
I need to know which one is better put
or offer
in case of linked blocking queue.
我需要知道哪个更好,put
或者offer
在链接阻塞队列的情况下。
Performance parameters are CPU utilization, memory and overall throughput.
性能参数是 CPU 利用率、内存和整体吞吐量。
Application usage is Real time system where there can be multiple incoming requests and less threads to handle where we will need to insert element in queue.
应用程序使用是实时系统,其中可以有多个传入请求和更少的线程来处理我们需要在队列中插入元素的地方。
I read Java docs of put and offer there was not much difference in internal application.
我阅读了 put 和 offer 的 Java 文档,内部应用程序没有太大区别。
采纳答案by Batty
Actually, you can't compare performance between these two, the offer
method is to just offer to the queue and it does not wait or waits for the time specified, but the put
method waits infinitely long until space is available, so their usage is different.
其实这两者的性能是无法比较的,offer
方法是只提供给队列,不等待或者等待指定的时间,但是put
方法是无限等待直到有空间可用,所以它们的用法是不同的。
Use put
where you cannot afford to loose an item, keeping in mind it will hold up your call stack, otherwise use offer
.
使用put
在您不能丢失项目的地方,请记住它会占用您的调用堆栈,否则使用offer
.
回答by Dark Knight
LinkedBlockingQueue is fully reentrant and the poll() method does not block the put(). However, the poll() method will spin. You probably should be using queue.take() which waits for there to be an item in the queue instead of returning null if the queue is empty.
LinkedBlockingQueue 是完全可重入的并且 poll() 方法不会阻塞 put()。但是, poll() 方法会旋转。您可能应该使用 queue.take() 等待队列中有一个项目,而不是在队列为空时返回 null。
Also consider this scenario, poll(long, TimeUnit) method will wait for an item to be added to the queue for the time period and returns null if the timer expires. That is a cleaner wait to wait for something in the queue.
还要考虑这种情况, poll(long, TimeUnit) 方法将在一段时间内等待将项目添加到队列中,并在计时器到期时返回 null。这是一个更干净的等待队列中的东西。
// wait for 2000ms for there to be an object in the queue
Object o = queue.poll(2000, TimeUnit.MILLISECONDS);
// no sleep necessary
return o;
回答by KyleM
The documentation makes the answer to this question clear. Offer doesn't wait and will "give up" if the queue has reached capacity. However, put will wait for space to become available -- in other words, it will block until space is available. Therefore offer is obviously faster since it never blocks.
文档清楚地回答了这个问题。优惠不会等待,如果队列已达到容量,将“放弃”。但是, put 将等待空间变得可用——换句话说,它会阻塞直到空间可用。因此,报价显然更快,因为它从不阻塞。