🔹 Introduction
Managing threads manually in Java can be complex and inefficient.
👉 Interviewers often ask:
“What is ExecutorService and why is it used?”
In this article, we will understand:
- Thread pools
- ExecutorService
- Real-world usage
🔹 What is ExecutorService?
ExecutorService is a framework in Java used to manage threads efficiently.
👉 It provides:
- Thread pooling
- Task scheduling
- Better resource management
🔹 Why Not Create Threads Manually?
❌ Creating threads manually:
- High overhead
- Difficult to manage
- Poor performance
👉 Solution: Thread Pool using ExecutorService
🔹 Creating ExecutorService
import java.util.concurrent.*;
public class Test {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(3);
for (int i = 1; i <= 5; i++) {
int task = i;
executor.execute(() -> {
System.out.println("Executing Task " + task + " by " + Thread.currentThread().getName());
});
}
executor.shutdown();
}
}
🔹 Output (Sample)
Executing Task 1 by pool-1-thread-1
Executing Task 2 by pool-1-thread-2
Executing Task 3 by pool-1-thread-3
...
🔍 Types of Thread Pools
🔹 Fixed Thread Pool
Executors.newFixedThreadPool(5);
👉 Fixed number of threads
🔹 Cached Thread Pool
Executors.newCachedThreadPool();
👉 Creates threads as needed
🔹 Single Thread Executor
Executors.newSingleThreadExecutor();
👉 Only one thread
🔹 Scheduled Thread Pool
Executors.newScheduledThreadPool(2);
👉 Runs tasks with delay
🔹 execute() vs submit()
| Method | Description |
|---|---|
| execute() | No return value |
| submit() | Returns Future |
🔹 Using submit()
Future<Integer> result = executor.submit(() -> 10 + 20);
System.out.println(result.get());
🔹 Key Methods
-
shutdown()→ stops accepting tasks -
shutdownNow()→ stops immediately -
awaitTermination()→ waits for completion
🔹 Time Complexity
- Depends on task execution
🔹 Key Takeaways
✔ ExecutorService manages thread pools
✔ Improves performance
✔ Avoids manual thread handling
✔ Very important for backend interviews
🔹 Conclusion
ExecutorService is a powerful tool for managing concurrency in Java and is widely used in real-world applications.
Simple and clear explanation, helped me revise quickly.
ReplyDeleteThanks a lot! 😊
DeleteIf you have any interview questions you faced, feel free to share—I’ll cover them in upcoming posts!