Working with Executor Framework
1. Creating Thread Pools
| Factory | Behavior |
|---|---|
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
| Method | Use |
|---|---|
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
| Type | Detail |
|---|---|
Callable<V> | Returns V, throws Exception |
Future<V>.get() | Blocks for result |
get(t, unit) | Times out |
cancel(mayInterrupt) | Best-effort |
isDone, isCancelled | Status check |
4. Configuring ThreadPoolExecutor
| Param | Effect |
|---|---|
| corePoolSize | Always-alive threads |
| maximumPoolSize | Cap when queue full |
| keepAliveTime | Idle non-core thread TTL |
| workQueue | Tasks awaiting execution |
| threadFactory | Customize thread creation |
| handler | RejectedExecutionHandler |
5. Using ScheduledExecutorService
| Method | Behavior |
|---|---|
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
| Method | Effect |
|---|---|
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)
| Policy | Behavior |
|---|---|
| AbortPolicy (default) | Throws RejectedExecutionException |
| CallerRunsPolicy | Runs in submitter thread (back-pressure) |
| DiscardPolicy | Silently drops |
| DiscardOldestPolicy | Drops head + retries |
8. Using CompletionService
| Method | Use |
|---|---|
submit(task) | Submit and track |
take() | Block for next completed Future |
poll(t, unit) | Timed |
9. Understanding Fork/Join Framework
| API | Use |
|---|---|
RecursiveTask<V> | Returns result |
RecursiveAction | void |
compute() | Override; split + invoke |
fork() / join() | Async + wait |
commonPool() | Shared pool |
| Work-stealing | Idle 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
| Customization | Reason |
|---|---|
| Name | Diagnostics in thread dumps |
| Daemon | JVM shutdown behavior |
| Priority | Background vs foreground |
| UncaughtExceptionHandler | Logging |
11. Using Work-Stealing Pools
| Aspect | Detail |
|---|---|
| Underlying | ForkJoinPool |
| Parallelism | Default = available cores |
| Best for | Many small CPU-bound tasks |
| Avoid | Long blocking I/O (use ManagedBlocker) |