Java BlockingQueue take() vs poll()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23379623/
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
Java BlockingQueue take() vs poll()
提问by isapir
When consuming values from a Queue in an infinite loop -- what would be more efficient:
在无限循环中使用队列中的值时 - 什么会更有效:
1) Blocking on the Queue until a value is available via take()
1) 在队列上阻塞,直到通过 take() 获得一个值
while (value = queue.take()) { doSomething(value); }
2) Sleeping for n milliseconds and checking if an item is available
2) 休眠 n 毫秒并检查项目是否可用
while (true) {
if ((value = queue.poll()) != null) { doSomething(value); }
Thread.sleep(1000);
}
采纳答案by awksp
Blocking is likely more efficient. In the background, the thread that initially calls take()
goes to sleep if there is no element available, letting other threads do whatever they need to do. The methods that add elements to the Queue will then wake up waiting threads when an element is added, so minimal time is spent checking the queue over and over again for whether an element is available.
阻塞可能更有效。在后台,take()
如果没有可用的元素,最初调用的线程会进入睡眠状态,让其他线程做他们需要做的任何事情。将元素添加到 Queue 的方法将在添加元素时唤醒等待的线程,因此花费最少的时间一遍又一遍地检查队列以确定元素是否可用。
回答by P Kumar
Be careful when you use take()
. If you are using take()
from a service and service has db connection.
使用时要小心take()
。如果您take()
从服务中使用并且服务具有数据库连接。
If take()
is returned after stale connection time out period then it will throw Stale connection exception.
如果take()
在过时连接超时后返回,则将抛出过时连接异常。
Use poll for predefined waiting time and add null check for returned object.
使用轮询预定义的等待时间并为返回的对象添加空检查。