Working with Executor Framework

1. Creating Thread Pools

FactoryBehavior
newFixedThreadPool(n)Bounded threads, unbounded queue
newCachedThreadPool()0..MAX threads, SynchronousQueue
newSingleThreadExecutor()Serial execution
newWorkStealingPool()ForkJoinPool
newVirtualThreadPerTaskExecutor() Java 21+One virtual thread per task

2. Using ExecutorService Interface

MethodUse
submit(Callable)Returns Future
execute(Runnable)Fire-and-forget
invokeAll(tasks)Wait all, returns futures
invokeAny(tasks)First success
close()AutoCloseable since Java 19

3. Using Callable and Future

TypeDetail
Callable<V>Returns V, throws Exception
Future<V>.get()Blocks for result
get(t, unit)Times out
cancel(mayInterrupt)Best-effort
isDone, isCancelledStatus check

4. Configuring ThreadPoolExecutor

ParamEffect
corePoolSizeAlways-alive threads
maximumPoolSizeCap when queue full
keepAliveTimeIdle non-core thread TTL
workQueueTasks awaiting execution
threadFactoryCustomize thread creation
handlerRejectedExecutionHandler

5. Using ScheduledExecutorService

MethodBehavior
schedule(r, delay, unit)One-shot
scheduleAtFixedRate(r, init, period, unit)Fixed start times
scheduleWithFixedDelay(r, init, delay, unit)Delay between completions
Warning: Uncaught exception in periodic task cancels all future runs — wrap in try/catch.

6. Shutting Down Executors

MethodEffect
shutdown()Stop accepting; finish running
shutdownNow()Interrupt running, return queued
awaitTermination(t, unit)Block for completion
close()shutdown + await indefinite

7. Handling Rejected Tasks (RejectedExecutionHandler)

PolicyBehavior
AbortPolicy (default)Throws RejectedExecutionException
CallerRunsPolicyRuns in submitter thread (back-pressure)
DiscardPolicySilently drops
DiscardOldestPolicyDrops head + retries

8. Using CompletionService

MethodUse
submit(task)Submit and track
take()Block for next completed Future
poll(t, unit)Timed

9. Understanding Fork/Join Framework

APIUse
RecursiveTask<V>Returns result
RecursiveActionvoid
compute()Override; split + invoke
fork() / join()Async + wait
commonPool()Shared pool
Work-stealingIdle threads steal from busy queues

Example: Sum array

class SumTask extends RecursiveTask<Long> {
    int[] a; int lo, hi;
    SumTask(int[] a, int lo, int hi) { this.a = a; this.lo = lo; this.hi = hi; }
    protected Long compute() {
        if (hi - lo < 1000) { long s = 0; for (int i = lo; i < hi; i++) s += a[i]; return s; }
        int m = (lo + hi) >>> 1;
        SumTask l = new SumTask(a, lo, m); l.fork();
        SumTask r = new SumTask(a, m, hi);
        return r.compute() + l.join();
    }
}

10. Creating Custom ThreadFactory

CustomizationReason
NameDiagnostics in thread dumps
DaemonJVM shutdown behavior
PriorityBackground vs foreground
UncaughtExceptionHandlerLogging

11. Using Work-Stealing Pools

AspectDetail
UnderlyingForkJoinPool
ParallelismDefault = available cores
Best forMany small CPU-bound tasks
AvoidLong blocking I/O (use ManagedBlocker)