The Executor Framework in Java provides a high-level API for managing and executing threads. Instead of manually creating and controlling threads, developers submit tasks to an executor service which handles thread creation, scheduling, and lifecycle management.
The framework is available in the java.util.concurrent package and supports different types of thread pools such as fixed, cached, and single-thread executors.
// Creating a fixed thread pool with 2 threads
ExecutorService executor = Executors.newFixedThreadPool(2);
// Submitting a simple Runnable task
executor.submit(() -> {
System.out.println("Task executed by: " + Thread.currentThread().getName());
});
// Shutting down the executor service
executor.shutdown();
// Callable task that returns a value
Callable task = () -> {
return 10 + 20;
};
// Single thread executor
ExecutorService service = Executors.newSingleThreadExecutor();
// Submitting Callable and getting Future
Future result = service.submit(task);
// Fetching result from Future
System.out.println(result.get());
service.shutdown();
Visualize how a Fixed Thread Pool (Size: 3) processes a queue of tasks.
The executor picks an available thread from the pool and runs the submitted task. For Callable, the result is returned using a Future object, allowing asynchronous processing.
Callable when a result is requiredFuture to check task completion