Multithreading: BlockingQueue.poll with a timeout avoids waiting forever

poll() with no arguments returns null immediately on an empty queue, while poll(timeout, unit) waits up to that long for an item before giving up. Both are safer than take(), which would block indefinitely.

Code
BlockingQueue<String> queue = new LinkedBlockingQueue<>();
String immediate = queue.poll();
String afterWait;
try {
    afterWait = queue.poll(30, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
    afterWait = null;
}
System.out.println("Poll on an empty queue (no wait): " + immediate);
System.out.println("Poll with a timeout, still empty: " + afterWait);
Output
Poll on an empty queue (no wait): null
Poll with a timeout, still empty: null
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms