简体   繁体   English

Java BlockingQueue take()vs poll()

[英]Java BlockingQueue take() vs poll()

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);
}

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. 在后台,如果没有可用的元素,最初调用take()的线程将进入休眠状态,让其他线程执行他们需要做的任何事情。 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. 然后,添加元素到Queue的方法将在添加元素时唤醒等待线程,因此花费最少的时间一遍又一遍地检查队列是否有元素可用。

Be careful when you use take() . 使用take()时要小心。 If you are using take() from a service and service has db connection. 如果您正在使用来自服务的take()并且服务具有数据库连接。

If take() is returned after stale connection time out period then it will throw Stale connection exception. 如果在过时连接超时后返回take() ,则会抛出Stale连接异常。

Use poll for predefined waiting time and add null check for returned object. 对预定义的等待时间使用poll并为返回的对象添加null检查。

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

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