Executor Framework
The Executor Framework is a higher-level way of managing and running threads in Java, using a pool of reusable threads instead of manually creating and managing individual Thread objects yourself.
1. What is the Executor Framework?
The Executor Framework is a higher-level way of managing and running threads in Java, using a pool of reusable threads instead of manually creating and managing individual Thread objects yourself.
2. Why is it used?
Manually creating a new thread for every single task can be wasteful and hard to manage at scale. The Executor Framework reuses a fixed set of threads efficiently, handling task scheduling for you.
3. Real-Life Example
Think of a call center with a fixed number of staff (a thread pool) handling an incoming stream of customer calls (tasks), rather than hiring a brand-new employee for every single call and letting them go right after.
4. Syntax
javaExecutorService executor = Executors.newFixedThreadPool(numberOfThreads); executor.execute(runnableTask); executor.shutdown();
5. Example Program
javaimport java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ExecutorDemo { public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(2); executor.execute(() -> System.out.println("Task 1 executed")); executor.execute(() -> System.out.println("Task 2 executed")); executor.shutdown(); } }
Output:
Task 1 executed
Task 2 executed6. Key Points to Remember
ExecutorServicemanages a pool of threads, reusing them for multiple tasks instead of creating new ones each time.- Always call
shutdown()once done submitting tasks, to allow the program to exit cleanly. - The Executor Framework is generally preferred over manually managing individual threads in real-world applications.