Search code examples
javamultithreadingblockingqueuewakeup

Should I explicitly wake a thread sucking on BlockingQueue.take() for performance?


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.


Solution

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