Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()

while (value = queue.take()) { doSomething(value); }

2) Sleeping for n milliseconds and checking if an item is available

while (true) {

    if ((value = queue.poll()) != null) { doSomething(value); }

    Thread.sleep(1000);
}
like image 418
isapir Avatar asked Apr 30 '14 04:04

isapir


People also ask

Is Java BlockingQueue thread-safe?

BlockingQueue implementations are thread-safe. All queuing methods achieve their effects atomically using internal locks or other forms of concurrency control.

What is the use of BlockingQueue in Java?

BlockingQueue is a java Queue that support operations that wait for the queue to become non-empty when retrieving and removing an element, and wait for space to become available in the queue when adding an element.

What is the difference between queue and BlockingQueue in Java?

A blocking queue is a queue which provides insert and remove operations that block or keep waiting until they are performed. The blocking queues are usually used in Producer-Consumer frameworks. This interface extends Queue and exists since Java 5. Null elements are not allowed.


2 Answers

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.

like image 157
awksp Avatar answered Oct 23 '22 01:10

awksp


Be careful when you use take(). If you are using take() from a service and service has db connection.

If take() is returned after stale connection time out period then it will throw Stale connection exception.

Use poll for predefined waiting time and add null check for returned object.

like image 44
P Kumar Avatar answered Oct 23 '22 03:10

P Kumar