40

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);
    }
    
4
  • 1
    as per my experience, the thread is best way to produce/consume message into blockingqueue. Commented Apr 30, 2014 at 4:38
  • how can java have a while loop with an assignment statement as the condition? Commented Jul 12, 2016 at 13:20
  • "Efficient" can be a lot of things: lower latency, higher throughput, less energy consuming (mobile), etc. You'll get better suited answers if you provide more background information. Commented Nov 14, 2017 at 3:51
  • how does "while (value = queue.take()) { doSomething(value); }" works ? Commented Apr 11, 2020 at 20:17

2 Answers 2

67

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It is better to use a solution with timeouts to not block a thread for an undetermined moment. Thus, a good implementation is to use the poll(timeout, unit) specially if the thread is ran by a ThreadPool and waiting for other task to do.
@Pierrick but isn't take() essentially sleeping the exact amount of time it should (i.e. until another task is available to do)? Seems to me like poll(timeout,unit) will achieve the same thing, except it would be waking up and performing checks unnecessarily.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.