isapir
isapir

Reputation: 23552

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

Upvotes: 39

Views: 49722

Answers (2)

P Kumar
P Kumar

Reputation: 37

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.

Upvotes: 2

awksp
awksp

Reputation: 11867

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.

Upvotes: 66

Related Questions