Executors and bounded queues
What you will learn
An executor separates submitting a task from deciding where and when it runs. ExecutorService adds result handles and lifecycle control. Use explicit capacity limits and a rejection policy so a burst of submissions cannot silently grow a queue without bound.
- Submit finite tasks and obtain results with a deadline.
- Explain queue saturation and a rejection policy.
- Cancel tasks cooperatively and close an owned executor.
Each example is a complete Main.java file. Use a fresh lab-owned directory: javac --release 21 -proc:none Main.java, then java Main. Only finite reviewed tasks are started. Use the included bounded pool and shutdown helpers where applicable. The fixture runner also enforces a process deadline.
Submit a result-bearing job
import java.util.concurrent.*;import java.util.concurrent.atomic.*;import java.util.concurrent.locks.*;public class Main { static ThreadPoolExecutor pool(int workers, int capacity) { return new ThreadPoolExecutor(workers, workers, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(capacity), new ThreadPoolExecutor.AbortPolicy()); } static void stop(ExecutorService pool) throws InterruptedException { pool.shutdown(); try { if (!pool.awaitTermination(3, TimeUnit.SECONDS)) { for (Runnable pending : pool.shutdownNow()) { if (pending instanceof Future<?> future) future.cancel(false); } if (!pool.awaitTermination(3, TimeUnit.SECONDS)) throw new AssertionError("workers still running"); } } catch (InterruptedException e) { for (Runnable pending : pool.shutdownNow()) { if (pending instanceof Future<?> future) future.cancel(false); } throw e; } } public static void main(String[] args) throws Exception { ThreadPoolExecutor workers = pool(2, 2); try { Future<Integer> total = workers.submit(() -> 7 * 6); System.out.println(total.get(3, TimeUnit.SECONDS)); } finally { stop(workers); } System.out.println(workers.isTerminated()); }}Expected output:
42trueThe caller receives a result and releases its owned pool. The deadline bounds the wait, not the runtime of an arbitrary task.
Tasks, workers and queues
Executor.execute accepts a Runnable; execution is not necessarily on a separate thread. ExecutorService.submit returns a Future, including for a Callable that returns a result. A successful Future.get observes the completed computation. In ThreadPoolExecutor, submissions first create workers up to the core count; after that they try the queue; if it is full, workers can grow up to the maximum; otherwise the rejection handler runs. A fixed-size pool created by Executors.newFixedThreadPool uses an unbounded queue. The examples instead use an ArrayBlockingQueue and AbortPolicy to expose overload. Backpressure means producers must slow down, reject or defer work when consumers cannot keep up. Never silently retry without a bound. CallerRunsPolicy can slow the caller but may block sensitive threads and discards tasks after shutdown; choose deliberately.
Results, cancellation and ownership
Future.get(timeout, unit) waits at most the specified time and can throw TimeoutException; it does not cancel the task. ExecutionException wraps a task failure; CancellationException signals cancellation. cancel(true) may interrupt a running worker; the worker must cooperate. isDone includes cancellation and exceptional completion. ExecutorService.shutdown rejects new work but lets submitted work finish; shutdownNow attempts interruption and returns queued tasks, not a guarantee of termination. Cancel returned Future tasks if callers still hold those handles. awaitTermination reports completion or timeout. The stop helper is for an owned pool of finite cooperative tasks; an interrupted coordinator requests shutdown and propagates interruption. The process-level timeout is a final guardrail. Do not shut down a shared executor that another component owns.
Capacity and schedules
Size pools using measured service time, arrival rate, CPU demand, downstream limits, queue delay and acceptable rejection rate; there is no universal thread-count formula. Monitor saturation and latency instead of treating queue size as a throughput solution. ScheduledExecutorService supports one-shot delay, fixed-rate scheduling (nominal start times), and fixed-delay scheduling (delay after completion). Periodic executions of the same task do not overlap in ScheduledThreadPoolExecutor; an uncaught task exception stops subsequent executions. Its delayed queue is unbounded, so bound the number of registered tasks and cancel unused handles. The example schedules only one finite task.
Reproduce queue saturation
import java.util.concurrent.*;import java.util.concurrent.atomic.*;import java.util.concurrent.locks.*;public class Main { static ThreadPoolExecutor pool(int workers, int capacity) { return new ThreadPoolExecutor(workers, workers, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(capacity), new ThreadPoolExecutor.AbortPolicy()); } static void stop(ExecutorService pool) throws InterruptedException { pool.shutdown(); try { if (!pool.awaitTermination(3, TimeUnit.SECONDS)) { for (Runnable pending : pool.shutdownNow()) { if (pending instanceof Future<?> future) future.cancel(false); } if (!pool.awaitTermination(3, TimeUnit.SECONDS)) throw new AssertionError("workers still running"); } } catch (InterruptedException e) { for (Runnable pending : pool.shutdownNow()) { if (pending instanceof Future<?> future) future.cancel(false); } throw e; } } public static void main(String[] args) throws Exception { ThreadPoolExecutor workers = pool(1, 1); CountDownLatch entered = new CountDownLatch(1), release = new CountDownLatch(1); try { Future<Integer> first = workers.submit(() -> { entered.countDown(); if (!release.await(3, TimeUnit.SECONDS)) throw new TimeoutException(); return 10; }); if (!entered.await(3, TimeUnit.SECONDS)) throw new AssertionError("not started"); Future<Integer> second = workers.submit(() -> 20); try { workers.submit(() -> 30); } catch (RejectedExecutionException e) { System.out.println("overloaded"); } release.countDown(); System.out.println(first.get(3, TimeUnit.SECONDS) + second.get(3, TimeUnit.SECONDS)); } finally { release.countDown(); stop(workers); } }}Expected output:
overloaded30A latch holds the only worker; the second task occupies the only queue slot. No sleep or assumed scheduling is needed. A real caller can return an overload response or defer with a finite retry budget.
Cancel a cooperative task
import java.util.concurrent.*;import java.util.concurrent.atomic.*;import java.util.concurrent.locks.*;public class Main { static ThreadPoolExecutor pool(int workers, int capacity) { return new ThreadPoolExecutor(workers, workers, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(capacity), new ThreadPoolExecutor.AbortPolicy()); } static void stop(ExecutorService pool) throws InterruptedException { pool.shutdown(); try { if (!pool.awaitTermination(3, TimeUnit.SECONDS)) { for (Runnable pending : pool.shutdownNow()) { if (pending instanceof Future<?> future) future.cancel(false); } if (!pool.awaitTermination(3, TimeUnit.SECONDS)) throw new AssertionError("workers still running"); } } catch (InterruptedException e) { for (Runnable pending : pool.shutdownNow()) { if (pending instanceof Future<?> future) future.cancel(false); } throw e; } } public static void main(String[] args) throws Exception { ThreadPoolExecutor workers = pool(1, 1); CountDownLatch entered = new CountDownLatch(1), exited = new CountDownLatch(1); try { Future<?> task = workers.submit(() -> { entered.countDown(); try { new CountDownLatch(1).await(3, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { exited.countDown(); } }); if (!entered.await(3, TimeUnit.SECONDS)) throw new AssertionError("not started"); System.out.println(task.cancel(true)); if (!exited.await(3, TimeUnit.SECONDS)) throw new AssertionError("not stopped"); System.out.println(task.isCancelled()); } finally { stop(workers); } }}Expected output:
truetrueThe latch verifies that the task exits, independently of the cancelled Future state. The task has a timed wait as a fallback.
Schedule one finite job
import java.util.concurrent.*;import java.util.concurrent.atomic.*;import java.util.concurrent.locks.*;public class Main { static void stop(ExecutorService pool) throws InterruptedException { pool.shutdown(); try { if (!pool.awaitTermination(3, TimeUnit.SECONDS)) { for (Runnable pending : pool.shutdownNow()) { if (pending instanceof Future<?> future) future.cancel(false); } if (!pool.awaitTermination(3, TimeUnit.SECONDS)) throw new AssertionError("workers still running"); } } catch (InterruptedException e) { for (Runnable pending : pool.shutdownNow()) { if (pending instanceof Future<?> future) future.cancel(false); } throw e; } } public static void main(String[] args) throws Exception { ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor(); try { ScheduledFuture<String> result = timer.schedule(() -> "report ready", 0, TimeUnit.MILLISECONDS); System.out.println(result.get(3, TimeUnit.SECONDS)); } finally { stop(timer); } }}Expected output:
report readyZero delay makes the task eligible immediately; the executor chooses the actual execution time. No exact timing assertion is made.
Common mistakes
Do not use unbounded submission as a capacity plan, ignore failed futures, assume get timeout cancels a task, or block on a child job submitted to the same saturated pool. Do not assume shutdownNow kills threads.
Practice
Use a two-worker, two-slot pool to compute 12 and 15 in separate tasks. Read both with a three-second timeout, print their sum, and stop the pool in finally.
Expected output:
27Compare your answer with the manual practice criteria.
Official reading: ExecutorService · ThreadPoolExecutor · Concurrency package. Java 25 execution remains unverified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Executors and bounded queues — knowledge check
Original concurrency questions. Java 21-compatible scope.
What happens when the only worker and bounded queue are full with AbortPolicy?
Does a timed Future.get cancel the work on timeout?
What does shutdown do?
What does cancel(true) request?
Which measurement helps choose queue capacity?