Java Tutorial

Executors & Thread Pools

Managing threads efficiently with ExecutorService and Callable

What is an ExecutorService?

In Java, creating a Thread is expensive for your computer's memory (~1MB per thread). If you create 1,000 threads for 1,000 tasks, your application will crash!
The ExecutorService (introduced in JAVA 5) provides a Thread Pool—a collection of "worker threads" that are kept alive and reused for different tasks. This is much faster and safer than creating threads manually.
java
import java.util.concurrent.*;

// Create 4 worker threads!
ExecutorService pool = Executors.newFixedThreadPool(4);

// Submit a task!
pool.submit(() -> {
    System.out.println("Task running via pool!");
});

pool.shutdown(); // Close when done!

Comparisons: Runnable vs. Callable

Wait! What if you want your background task to return a value? A normal Runnable cannot send data back. Use a Callable instead.
InterfaceReturns...Throws...Use Case
RunnablevoidNo ExceptionsFire-and-forget.
Callable<V>V (any type)ExceptionsTask with a result.

Handling Results: The Future<V>

When you submit a Callable to a pool, it returns a Future object—a "I'll give it to you soon" promise. You can check if the task is finished and get the result later.
java
// Logic to calculate a total later!
Callable<Integer> task = () -> 2 + 2;

Future<Integer> res = pool.submit(task);
// ... do other work ...
int total = res.get(); // BLOCKS until the result is ready!

Most Common Thread Pool Types

Pool TypeBehaviorBest Use Case...
FixedFixed number of threads.Reliable, stable load.
CachedCreates threads as needed.High number of short tasks.
ScheduledRuns periodic tasks.Timed intervals (e.g., a clock).
SingleExactly ONE background thread.Sequential execution.

Summary

TermDescription
ExecutorHigher-level API for running tasks
PoolA collection of pre-made background threads
TasksRunnable or Callable objects
FutureA placeholder for a result that isn't ready yet
shutdown()Gently stop the pool; let current tasks finish
invokeAll()Run many tasks and wait for them all!
Best ForServers, heavy processing, safe multi-tasking
EfficiencyAvoid the cost of re-creating threads
ControlLimit how much memory your app can use!
ModernVirtual Threads (Java 21+) use a unique executor!
QueueTasks wait in a queue if all threads are busy
RejectIf the queue is full, the task is "rejected"!
Time Outres.get(5, SECONDS) (Stop waiting if it takes too long!)
CompletabCompletableFuture (The ultimate way to link async work!)
StandardEstablished and trusted worldwide for 25+ years
ManagedJVM handles all thread scheduling for you
ContextFewer threads = less overhead for the CPU
ResourceA pool of 10 threads is a fixed memory cost
HierarchyExService -> ScheduledExService
LifecycleSubmit -> Execute -> Shutdown -> Finish