Search code examples
javaqueueblockingqueue

How to stop methods put() and take() from 'endless waiting'?


In BlockingQueue implementations we know that methods put() and take() have blocking nature.

What is your advice in solving their endless wait state? What if there are no more items to read and take() is called for example. My program will run forever. How would you solve this? Any tips?


Solution

  • Use the offer and poll methods of the BLockingQueue. They allow you to specify a timeout for both operations.

    // returns false if it could not push after 1 second
    blockingQueue.offer(5, 1, TimeUnit.SECONDS);
    
    /// returns null if no item was received after 1 second
    blockingQueue.poll(1, TimeUnit.SECONDS);
    

    If you don't want a timeout you can use the overloaded methods which will return immediately with the same return behavior (offer poll)

    // returns false if it could not push
    blockingQueue.offer(5);
    
    /// returns null if no item was received
    blockingQueue.poll();
    

    Be careful about checking if the return of poll is null. Depending on the structure of the project, you might want to look into java Optional to help with proper null checking.