Java Executor Framework simplifies multithreading by managing thread creation, execution, and lifecycle efficiently. Instead of manually creating and managing threads, the Executor framework allows developers to focus on the tasks themselves.
In this article, we’ll explore ExecutorService, ThreadPoolExecutor, Callable, Future, CompletableFuture, and other advanced concurrency utilities with examples.
1️⃣ What is ExecutorService in Java?
ExecutorService is a part of the java.util.concurrent package.
It is a higher-level replacement for directly creating and managing threads using the Thread class.
It manages a pool of worker threads and executes submitted tasks asynchronously.
ExecutorService executor = Executors.newFixedThreadPool(3);
executor.submit(() -> {
System.out.println("Task executed by " + Thread.currentThread().getName());
});
executor.shutdown();
2️⃣ Difference between Executor, ExecutorService, and Executors
| Interface/Class | Description |
|---|---|
Executor | Base interface that executes Runnable tasks. |
ExecutorService | Sub-interface of Executor that adds lifecycle management (shutdown, submit, invokeAll, etc.) |
Executors | Utility class providing factory methods to create different types of thread pools. |
3️⃣ What is ThreadPoolExecutor?
ThreadPoolExecutor is the core implementation class behind all thread pools created by the Executors utility.
It manages a pool of threads with parameters like core size, maximum size, and queue capacity.
ExecutorService executor = new ThreadPoolExecutor(
2, 4, 10, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(2)
);
This gives fine-grained control over thread creation, queueing, and rejection policies.
4️⃣ Difference between Fixed Thread Pool and Cached Thread Pool
| Feature | Fixed Thread Pool | Cached Thread Pool |
|---|---|---|
| Created Using | Executors.newFixedThreadPool(n) | Executors.newCachedThreadPool() |
| Thread Count | Fixed number of threads | Creates new threads as needed |
| When to Use | Stable number of concurrent tasks | Many short-lived, unpredictable tasks |
5️⃣ How do you gracefully shut down a thread pool?
Use shutdown() or shutdownNow():
executor.shutdown(); // no new tasks, waits for running tasks to finish
if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
executor.shutdownNow(); // forcefully stop
}
6️⃣ What is Callable and how is it different from Runnable?
| Feature | Runnable | Callable |
|---|---|---|
| Return Value | No | Returns a result (generic) |
| Exception Handling | Cannot throw checked exceptions | Can throw checked exceptions |
Callable<Integer> task = () -> {
return 5 + 10;
};
Future<Integer> result = executor.submit(task);
System.out.println("Result: " + result.get());
7️⃣ What is Future in Java?
Future represents the result of an asynchronous computation.
You can check if the task is done, cancel it, or get the result.
Future<String> future = executor.submit(() -> "Task Complete");
System.out.println(future.get()); // waits until result is available
8️⃣ What is CompletableFuture?
CompletableFuture is an enhanced Future introduced in Java 8 that supports asynchronous and reactive programming.
CompletableFuture.supplyAsync(() -> "Hello")
.thenApply(str -> str + " World")
.thenAccept(System.out::println);
Output: Hello World
9️⃣ How do you chain tasks using thenApply() and thenRun()?
thenApply()— transforms the result and returns a new value.thenRun()— runs a task after completion but doesn’t receive the result.
CompletableFuture.supplyAsync(() -> 10)
.thenApply(n -> n * 2)
.thenRun(() -> System.out.println("Task Completed"));
🔟 Difference between submit() and execute() methods
| Method | Description |
|---|---|
execute() | Accepts only Runnable, no return value. |
submit() | Accepts Runnable or Callable, returns a Future object. |
11️⃣ What is ForkJoinPool in Java?
ForkJoinPool is a special type of thread pool designed for parallel computation — it divides a task into smaller subtasks (forks), executes them in parallel, and combines (joins) results.
ForkJoinPool pool = new ForkJoinPool();
pool.submit(() -> System.out.println("Parallel task executed"));
pool.shutdown();
12️⃣ Difference between ForkJoinPool and ThreadPoolExecutor
| Feature | ThreadPoolExecutor | ForkJoinPool |
|---|---|---|
| Work Model | Task Queue | Work-Stealing |
| Best For | Independent tasks | Recursive parallel tasks |
13️⃣ What is a parallel stream in Java 8?
A parallel stream splits the data source into multiple parts and processes them in parallel using the ForkJoinPool.
List<Integer> list = Arrays.asList(1,2,3,4,5);
list.parallelStream().forEach(System.out::println);
14️⃣ How does parallel stream use ForkJoinPool internally?
Parallel streams use the common ForkJoinPool under the hood to execute tasks in multiple threads.
You can control the pool size using:
System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "4");
15️⃣ What is the common pool in ForkJoin framework?
The common pool is a shared ForkJoinPool used by parallel streams and CompletableFuture tasks when no custom pool is provided.
16️⃣ What is thread confinement?
Thread confinement means restricting access of a variable or object to a single thread.
Since only one thread can access it, synchronization is not required.
17️⃣ What is thread safety?
Thread safety means that multiple threads can access and modify an object safely without causing inconsistent state or race conditions.
18️⃣ How to make a class thread-safe?
- Use synchronization or locks.
- Use immutable objects.
- Use atomic variables or concurrent collections.
19️⃣ What are immutable objects and how do they help in multithreading?
Immutable objects cannot be modified after creation, which makes them inherently thread-safe.
final class Employee {
private final String name;
Employee(String name) { this.name = name; }
public String getName() { return name; }
}
Multiple threads can safely access immutable objects without synchronization.
20️⃣ What is ThreadLocal and when would you use it?
ThreadLocal provides thread-confined variables — each thread gets its own independent copy.
ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);
threadLocal.set(10);
System.out.println(threadLocal.get());
Used in cases like user sessions, logging context, and transaction management.
21️⃣ What are concurrency utilities in java.util.concurrent package?
This package provides powerful tools for multithreading, including:
- ExecutorService, ThreadPoolExecutor
- CountDownLatch, CyclicBarrier, Semaphore, Phaser
- BlockingQueue, ConcurrentHashMap
- Atomic classes (AtomicInteger, etc.)
22️⃣ What is the purpose of BlockingQueue?
BlockingQueue is a thread-safe queue that blocks threads when the queue is full (on insert) or empty (on remove).
BlockingQueue<String> queue = new ArrayBlockingQueue<>(2);
queue.put("Task1");
queue.take();
23️⃣ Difference between ArrayBlockingQueue and LinkedBlockingQueue
| Feature | ArrayBlockingQueue | LinkedBlockingQueue |
|---|---|---|
| Internal Structure | Array-based | Linked-list-based |
| Capacity | Fixed | Optional (unbounded) |
| Performance | Faster for small capacity | Better for dynamic load |
24️⃣ What is ConcurrentHashMap? How does it work internally?
ConcurrentHashMap is a thread-safe version of HashMap that allows concurrent reads and segmented locking for writes.
- Uses multiple segments (locks per bucket).
- Read operations don’t require locking.
- Write operations lock only specific segments.
25️⃣ What is a CopyOnWriteArrayList and where to use it?
CopyOnWriteArrayList creates a fresh copy of the list every time it’s modified.
It’s ideal for scenarios where reads are frequent but writes are rare.
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
list.add("A");
list.add("B");
System.out.println(list);
✅ Conclusion
The Executor Framework and concurrency utilities like ForkJoinPool, CompletableFuture, and BlockingQueue form the backbone of modern Java multithreading.
Mastering these will not only help you in interviews but also in building scalable, high-performance systems.
Next Read:
👉 Top 25 Basic Multithreading Interview Questions with detailed answers
👉 Top 25 Advance Multithreading Interview Questions with detailed answers
0 Comments