Handle a full work queue in Java

Offer reports whether an item fits immediately. Poll returns the oldest queued item, or null once the queue is empty.

A simple example

Offer A, then B

  1. Start with Queue with room for one item
  2. Do this Offer A, then B
  3. Result Only A fits
Until A is removed the queue has no free slot.

Apply it to a real problem

  1. Start with One work slot and two jobs
  2. Do this Offer report, then invoice
  3. Result Report accepted, invoice waits for a retry
The second offer returns false, so the application must decide when to retry.
Advertisements

Run the example

Save as Main.java and run java Main.java with JDK 21.

Main.java
import java.util.concurrent.ArrayBlockingQueue;

public class Main {
    public static void main(String[] args) throws Exception {
        var jobs = new ArrayBlockingQueue<String>(1);
        System.out.println(jobs.offer("report"));
        System.out.println(jobs.offer("invoice"));
        System.out.println(jobs.poll());
        System.out.println(jobs.poll());
    }
}
Output
true
false
report
null

Official Java documentation