Working with Executor Framework
1. Understanding Executor Interface
| Method | Detail |
|---|---|
execute(Runnable) | Submit fire-and-forget |
| Implementations | ThreadPoolExecutor, ForkJoinPool, etc. |
2. Using ExecutorService
| Method | Returns |
|---|---|
submit(Runnable) | Future<?> |
submit(Callable) | Future<V> |
invokeAll(tasks) | List of Futures |
invokeAny(tasks) | First successful |
shutdown() | Graceful |
shutdownNow() | Interrupt running |
awaitTermination(t,u) | Wait for completion |
3. Creating Fixed Thread Pool
Example: Fixed pool
try (ExecutorService pool = Executors.newFixedThreadPool(8)) {
var futures = tasks.stream().map(pool::submit).toList();
for (var f : futures) results.add(f.get());
} // auto-shutdown via Java 19+ AutoCloseable
| Aspect | Detail |
|---|---|
| Threads | Fixed count, reused |
| Queue | Unbounded LinkedBlockingQueue (memory risk) |
| Use | CPU-bound, predictable load |
4. Creating Cached Thread Pool
| Aspect | Detail |
|---|---|
| Threads | 0 to Integer.MAX_VALUE |
| Idle timeout | 60s |
| Queue | SynchronousQueue (no buffering) |
| Risk | Unbounded thread creation under load |
5. Creating Scheduled Thread Pool
Example: Scheduled tasks
ScheduledExecutorService sched = Executors.newScheduledThreadPool(2);
sched.schedule(task, 5, TimeUnit.SECONDS);
sched.scheduleAtFixedRate(task, 0, 1, TimeUnit.MINUTES);
sched.scheduleWithFixedDelay(task, 0, 30, TimeUnit.SECONDS);
| Method | Behavior |
|---|---|
schedule(t,d,u) | One-shot delay |
scheduleAtFixedRate | Period from start |
scheduleWithFixedDelay | Delay between completions |
6. Creating Single Thread Executor
| Aspect | Detail |
|---|---|
| Threads | Exactly one |
| Use | Sequential ordering guarantee |
| Replacement | If thread dies, a new one is created |
7. Creating Virtual Thread Per Task Executor JAVA 21+
Example: Virtual threads
try (ExecutorService vexec = Executors.newVirtualThreadPerTaskExecutor()) {
IntStream.range(0, 100_000).forEach(i ->
vexec.submit(() -> { fetchUrl(i); return null; })
);
}
| Aspect | Detail |
|---|---|
| Cost | Lightweight — millions of threads OK |
| Best for | I/O-bound (HTTP, DB) workloads |
8. Submitting Tasks
| Method | Behavior |
|---|---|
execute(r) | No future returned |
submit(r/c) | Returns Future |
| Rejected | RejectedExecutionException (after shutdown / queue full) |
9. Using Future Interface
| Method | Detail |
|---|---|
get() / get(t, u) | Block for result |
isDone() / isCancelled() | Status |
cancel(mayInterrupt) | Try cancel |
| Exception | ExecutionException wraps task exception |
10. Cancelling Tasks
| Aspect | Detail |
|---|---|
| Pre-execution | Removes from queue |
| During execution | Sets interrupt flag (if mayInterrupt) |
| Tasks must check | Thread.interrupted() |
11. Shutting Down Executors
| Method | Behavior |
|---|---|
shutdown() | No new tasks; finish queued |
shutdownNow() | Interrupt running, return queued |
close() JAVA 19+ | shutdown + awaitTermination |
12. Configuring ThreadPoolExecutor
Example: Custom pool
var pool = new ThreadPoolExecutor(
4, // corePoolSize
16, // maximumPoolSize
60L, TimeUnit.SECONDS, // keepAliveTime
new ArrayBlockingQueue<>(100), // bounded queue
new ThreadFactoryBuilder().setNameFormat("worker-%d").build(),
new ThreadPoolExecutor.CallerRunsPolicy() // backpressure
);
| Param | Detail |
|---|---|
| corePoolSize | Always-on threads |
| maximumPoolSize | Upper bound |
| keepAliveTime | Idle timeout for above-core threads |
| workQueue | Use bounded for safety |
| RejectedExecutionHandler | Abort/CallerRuns/Discard/DiscardOldest |
13. Using ForkJoinPool
| Aspect | Detail |
|---|---|
| Algorithm | Work-stealing |
| Common pool | Used by parallel streams & CompletableFuture |
| Tasks | RecursiveTask / RecursiveAction |
14. Implementing Producer-Consumer Pattern
Example: Producer-Consumer
BlockingQueue<Item> queue = new LinkedBlockingQueue<>(100);
Runnable producer = () -> {
while (running) queue.put(produce());
};
Runnable consumer = () -> {
while (true) process(queue.take());
};
| Element | Role |
|---|---|
| BlockingQueue | Bounded buffer |
| Producer | put (blocks if full) |
| Consumer | take (blocks if empty) |
| Poison pill | Sentinel for shutdown |