![]() |
VOOZH | about |
The Executor Framework is a high-level concurrency utility introduced in Java 5 that simplifies thread management and task execution. Instead of creating and managing threads manually, developers can submit tasks to an executor, which handles thread scheduling and execution efficiently.
The Executor Framework consists of several core interfaces and classes that simplify concurrent programming in Java.
Executor Interface is root interface of the framework is used to execute submitted tasks without explicitly creating threads. Defines a single method:
Executor executor = command -> new Thread(command).start();
executor.execute(() -> System.out.println("Task executed"));
The ExecutorService extends the Executor interface and provides advanced methods for task management, such as submitting tasks that return results and controlling executor shutdown.
ExecutorService service = Executors.newFixedThreadPool(2);
service.submit(() -> System.out.println("Running a task"));
service.shutdown();
ScheduledExecutorService Interface is extends ExecutorService and supports task scheduling, running tasks periodically or after a delay.
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(task, 0, 5, TimeUnit.SECONDS);
ThreadPoolExecutor is the most commonly used implementation of ExecutorService. It manages a pool of worker threads to execute tasks efficiently, reusing threads to reduce overhead.
ExecutorService executor = Executors.newFixedThreadPool(3);
executor.execute(task);
A base class that provides default implementations for ExecutorService methods. Simplifies creating custom executors by handling common functionalities like submit() and invokeAll().
The Executors utility class provides factory methods to easily create different kinds of thread pools. Each type is designed for specific concurrency requirements.
| Executor Type | Description | Syntax Example |
|---|---|---|
| SingleThreadExecutor | Creates a thread pool with a single thread that executes tasks sequentially. | ExecutorService executor = Executors.newSingleThreadExecutor(); |
| FixedThreadPool | Creates a pool with a fixed number of threads. Excess tasks are queued until a thread becomes available. | ExecutorService pool = Executors.newFixedThreadPool(2); |
| CachedThreadPool | Creates threads as needed and reuses idle ones. Suitable for many short-lived asynchronous tasks. | ExecutorService pool = Executors.newCachedThreadPool(); |
| ScheduledThreadPool | Executes tasks periodically or after a specified delay. | ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); |
Creating and Executing a Simple Executor in which we will create a task and execute it in a fixed pool
Hi GeeksForGeeks!