39

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);
    }
    
Gray
  • 115,027
  • 24
  • 293
  • 354
isapir
  • 21,295
  • 13
  • 115
  • 116

2 Answers2

65

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.

awksp
  • 11,764
  • 4
  • 37
  • 44
  • 20
    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 Dec 18 '15 at 16:28
  • 3
    @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. – Nom1fan Feb 01 '20 at 08:29
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.

Regolith
  • 2,944
  • 9
  • 33
  • 50
P Kumar
  • 37
  • 1