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
- Start with Queue with room for one item
- Do this Offer A, then B
- Result Only A fits
Apply it to a real problem
- Start with One work slot and two jobs
- Do this Offer report, then invoice
- Result Report accepted, invoice waits for a retry
Advertisements
Run the example
Save as Main.java and run java Main.java with JDK 21.
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());
}
}
true false report null