Skip to main content

Java Interview Question: What is ExecutorService in Java? Thread Pool Explained (With Examples)

 

🔹 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()

MethodDescription
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.

Comments

  1. Simple and clear explanation, helped me revise quickly.

    ReplyDelete
    Replies
    1. Thanks a lot! 😊
      If you have any interview questions you faced, feel free to share—I’ll cover them in upcoming posts!

      Delete

Post a Comment

Popular posts from this blog

Top Java Interview Question: First Non-Repeating Character in a String

  🔹 Introduction Java interviews often include string-based questions. One of the most commonly asked questions is: 👉 Find the first non-repeating character in a string. In this article, we will solve it step by step in a simple and easy-to-understand way. 🔹 Problem Statement Given a string, find the first character that does not repeat. Example: Input: aabbcde Output: c 🔹 Approach To solve this problem efficiently: Count frequency of each character Maintain insertion order Traverse again to find the first character with frequency = 1 👉 We use LinkedHashMap because: It maintains insertion order Helps us find the first non-repeating character 🔹 Java Code import java . util . *; public class FirstNonRepeating { public static void main ( String [] args ) { String str = "aabbcde" ; Map < Character , Integer > map = new LinkedHashMap <>(); // Count frequency for ( char ch : str . to...

Java Interview Question: Separate Even and Odd Numbers Using Streams (With Examples)

  🔹 Introduction Separating even and odd numbers is a common Java interview question. It helps test your understanding of Java Streams, filtering, and partitioning . 👉 In this article, we will solve this using: Traditional approach Java Streams (modern approach) 🔹 Problem Statement Given a list of integers, separate even and odd numbers. Example: Input: [1, 2, 3, 4, 5, 6] Output: Even: [2, 4, 6], Odd: [1, 3, 5] 🔹 Approach 1: Using Loop (Basic) 💡 Explanation Traverse list Check number % 2 Store in separate lists 👨‍💻 Java Code import java . util . *; public class EvenOdd { public static void main ( String [] args ) { List < Integer > list = Arrays . asList ( 1 , 2 , 3 , 4 , 5 , 6 ); List < Integer > even = new ArrayList <>(); List < Integer > odd = new ArrayList <>(); for ( int num : list ) { if ( num % 2 == 0 ) { even . add ( num )...

Java Interview Question: Check if a String is a Palindrome

 🔹 Introduction String problems are very common in Java interviews. One of the easiest yet frequently asked questions is: 👉 Check whether a given string is a palindrome. Let’s understand how to solve it step by step. 🔹 Problem Statement A string is called a palindrome if it reads the same forward and backward. Example: Input: madam Output: Palindrome Input: hello Output: Not a Palindrome 🔹 Approach 1: Using Two Pointers (Best Method) Start one pointer from the beginning Start another pointer from the end Compare characters If all match → Palindrome 🔹 Java Code (Two Pointer Approach) public class PalindromeCheck { public static void main ( String [] args ) { String str = "madam" ; int left = 0 ; int right = str . length () - 1 ; boolean isPalindrome = true ; while ( left < right ) { if ( str . charAt ( left ) != str . charAt ( right )) { isPalindr...