4

I understand that having a thread sucking for elements of a BlockingQueue using the take() method will wait for an element to be available (unless it is interrupted).

I have two questions:

i) Is the thread automatically woken-up as soon as an element becomes available or is there a delay (i.e., the thread checks itself later)?

ii) If there is a delay, does it make sense to wake up the thread (by interrupting it explicitly for example)? I am thinking about latency and performance.

Luke Girvin
  • 13,221
  • 9
  • 64
  • 84
Jérôme Verstrynge
  • 57,710
  • 92
  • 283
  • 453

1 Answers1

4

There is no additional delay. The method call returns if a element is available or the thread is interrupted.

Retrieves and removes the head of this queue, waiting if necessary until an element becomes available.

Returns:
    the head of this queue 
Throws:
    InterruptedException - if interrupted while waiting

The BlockinQueue is doing this automatically (impl. of ArrayBlockingQueue).

// in add etc.
notEmpty.signal();

// in take()
while(count == 0) 
  notEmpty.await();
Tobias
  • 9,170
  • 3
  • 24
  • 30
  • @DownVoter: Please leave a comment. – Tobias Oct 08 '11 at 15:49
  • I can only assume that the downvoter, (no, wasn't me:), is objecting to 'There is no delay' - there may be a scheduling delay. The consumer thread is made ready when the producer posts an item, but will not run immediately if the set of ready/running threads of higher priority than the consumer has the same or more elements than the number of cores. Either way, interrupting or other such fiddling with the thread will not change anything. The only way of minimizing any delay is to ensure that the consumer has a high enough priority. – Martin James Oct 08 '11 at 18:14
  • thanks for the explanation. I edited my answer because I was refering to additional delay which could be speeded up. – Tobias Oct 08 '11 at 18:17