ExecutorService and Callable
0 241
โ๏ธ Introduction to ExecutorService and Callable in Java
In Java, managing multiple threads manually can become tedious and error-prone. This is where the ExecutorService and Callable interfaces come into play.
They are part of the java.util.concurrent package and provide a robust framework for handling asynchronous task execution, thread pooling, and returnable results.
๐ง What is ExecutorService?
ExecutorService is a higher-level replacement for working directly with threads. It simplifies thread management by offering a pool of threads to execute submitted tasks.
It decouples task submission from execution, allowing better control and optimization of thread resources.
๐ Common Methods in ExecutorService
submit()
โ Submits a task for execution and returns aFuture
.invokeAll()
โ Executes a collection ofCallable
tasks and returns a list ofFuture
objects.shutdown()
โ Initiates an orderly shutdown where previously submitted tasks are executed but no new tasks are accepted.
๐งต What is Callable?
Callable
is a functional interface similar to Runnable
, but it can return a result and throw a checked exception.
It is used when you want a thread to execute a task and return some value.
๐ Callable vs Runnable
Feature | Runnable | Callable |
Return Value | No | Yes |
Exception Handling | Cannot throw checked exceptions | Can throw checked exceptions |
Method | run() | call() |
๐ป Example: Using ExecutorService and Callable
import java.util.concurrent.*;
public class ExecutorExample {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
Callable<String> task = () -> {
Thread.sleep(1000);
return "Task completed!";
};
Future<String> future = executor.submit(task);
System.out.println("Task submitted...");
// Wait and get the result
String result = future.get();
System.out.println(result);
executor.shutdown();
}
}
๐ Handling Future Results
The Future
object represents the result of an asynchronous computation. You can use its methods to check if the task is done, retrieve the result, or even cancel the task.
get()
โ Waits if necessary for the computation to complete and returns the result.isDone()
โ Returns true if the task is completed.cancel()
โ Attempts to cancel the execution of the task.
๐ Example with Multiple Callables
import java.util.*;
import java.util.concurrent.*;
public class MultipleTasks {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(3);
List<Callable<String>> taskList = Arrays.asList(
() -> "Task 1",
() -> "Task 2",
() -> "Task 3"
);
List<Future<String>> results = executor.invokeAll(taskList);
for (Future<String> f : results) {
System.out.println(f.get());
}
executor.shutdown();
}
}
๐ Advantages of ExecutorService and Callable
- Improved thread reuse with thread pools.
- Flexible task submission using different Executor types.
- Efficient result handling via
Future
. - Better error management with checked exceptions in
Callable
.
โ Conclusion
ExecutorService and Callable form a powerful duo in Javaโs concurrency toolkit. They simplify thread handling, enable efficient resource usage, and support asynchronous programming with result tracking.
By leveraging them properly, developers can build scalable and maintainable multithreaded applications.
If youโre passionate about building a successful blogging website, check out this helpful guide at Coding Tag โ How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!

Share:
Comments
Waiting for your comments