Java Materials
← Core Java · Chapter 15

Executors and thread-pool design

Executor schedules Runnable work. ExecutorService adds futures and lifecycle; ScheduledExecutorService adds delayed and periodic tasks. Callable can return a value and checked failure. execute submits fire-and-forget work; submit captures failures in a Future, so ignored futures can hide exceptions.

Admission, capacity and rejection

Definition:

A bounded executor has a policy for admitting, queueing and rejecting work under load.

Explanation:

ThreadPoolExecutor prefers queueing once core workers exist.

Illustration image:

Admission, capacity and rejection. Core slots · Bounded queue slots · Extra slots if full · Reject if all occupiedAdmission, capacity and rejectionSource or actorCore slotsFirst boundaryBounded queue slotsInspected stateExtra slots if fullObservable effectReject if all occupied
Core slots · Bounded queue slots · Extra slots if full · Reject if all occupied

Example:

Worked Java example · see surrounding context in notes
var pool = new java.util.concurrent.ThreadPoolExecutor(
    2,4,30,java.util.concurrent.TimeUnit.SECONDS,
    new java.util.concurrent.ArrayBlockingQueue<>(8),
    new java.util.concurrent.ThreadPoolExecutor.AbortPolicy());
pool.shutdown();

Expected behavior. The configured upper bounds are four workers and eight queued tasks; submission after shutdown is rejected.

Internal working:

With an unbounded queue, max workers is largely irrelevant and queue age rises when arrival rate exceeds service rate. Use a bounded queue, reserve capacity for other paths, and translate rejection at the proper request boundary. CallerRunsPolicy is unsafe on a nonblocking event loop because it executes work inside the caller.

Interview questions:

Why can an unbounded queue make maximumPoolSize ineffective?

After the core workers exist, queue offers keep succeeding, so the executor rarely grows past core.

Pool starvation and isolation

Definition:

Thread-pool starvation happens when queued work cannot get the workers needed to complete it.

Explanation:

A pool can stall even when no locks are deadlocked.

Illustration image:

The only worker is blocked in get. Its child is eligible to run but remains queued because the parent holds the executor slot. A worker waits on its own poolSingle workerPool queueparent startssubmit childchild.get()child waitsNo worker is available
The only worker is blocked in get. Its child is eligible to run but remains queued because the parent holds the executor slot.

Example:

Worked Java example · see surrounding context in notes
var first = java.util.concurrent.CompletableFuture.supplyAsync(api::profile, ioPool);
var second = java.util.concurrent.CompletableFuture.supplyAsync(api::balance, ioPool);
return first.thenCombine(second, Overview::new);

Expected behavior. The caller can await the composite at a suitable boundary without occupying a worker just to wait for work queued behind it.

Internal working:

A typical cause is synchronous Future.get inside tasks that enqueue their children onto that same saturated pool. Use independent composition, eliminate dependency-on-self or isolate executors. Track active count, time spent queued, queue age and completed throughput.

Interview questions:

Why can parent tasks block a pool without a monitor deadlock?

All workers can wait on child tasks queued behind them, leaving no free worker for those children.

Scheduling and graceful shutdown

Definition:

Graceful shutdown stops admission, gives accepted tasks time to finish and handles incomplete work.

Explanation:

Fixed-rate schedules aim at periodic start times; fixed-delay schedules wait after completion.

Illustration image:

Scheduling and graceful shutdown. Stop admission · Await termination · Request interruption · Reconcile unfinished workScheduling and graceful shutdownSource or actorStop admissionFirst boundaryAwait terminationInspected stateRequest interruptionObservable effectReconcile unfinished work
Stop admission · Await termination · Request interruption · Reconcile unfinished work

Example:

Worked Java example · see surrounding context in notes
pool.shutdown();
try {
    if (!pool.awaitTermination(2, java.util.concurrent.TimeUnit.SECONDS)) {
        var neverStarted = pool.shutdownNow();
        recordAbandoned(neverStarted);
    }
} catch (InterruptedException interrupted) {
    pool.shutdownNow();
    Thread.currentThread().interrupt();
}

Expected behavior. Never-started tasks can be reconciled. Running tasks still have to observe interruption.

Internal working:

An uncaught error suppresses later invocations of that periodic task. Catch and classify expected errors that should not stop the schedule. During shutdown, track accepted work that never starts and protect externally durable outcomes from duplicate retry.

Interview questions:

Does shutdownNow guarantee that running tasks stop?

No. It interrupts running workers on a best-effort basis and returns tasks that never started.

Reference subtopics

Admission, sizing and scheduling

ThreadPoolExecutor normally creates core workers first, then prefers enqueueing, then grows toward maximum when enqueueing fails, then rejects. An unbounded queue can prevent growth beyond core and hold unbounded work. Use bounded capacity, named threads, worker limits and documented overload behavior. Keep-alive applies to idle excess workers by default; core timeout can be enabled.

Executor choices

Fixed pools bound workers but their standard factory queues work without a capacity limit. Cached pools can create many workers. Single-threaded executors serialize tasks. Scheduled pools run delayed work. Work-stealing suits divide-and-conquer. Java 21 virtual-thread-per-task executors create a new virtual thread per task; limit the scarce backend separately.

Rejection and lifecycle

AbortPolicy surfaces rejection; CallerRunsPolicy can slow the producer but may block a request or event-loop thread and discards work after shutdown. scheduleAtFixedRate targets a period; scheduleWithFixedDelay waits after completion. Uncaught exceptions suppress subsequent runs of that periodic task. On shutdown, stop admission, await a bounded drain, then attempt shutdownNow and inspect outstanding work.

Starvation and capacity

CPU-bound work is constrained by cores. Blocking I/O needs concurrency sized around dependency latency and capacity. Isolate workloads with different failure modes. A task on a bounded executor should not synchronously wait for a child queued on the same saturated executor. Check queue age and completion rate, not just active count.

Run the complete Java labs ↗ · Java reference ↗