ExecutorService and Callable
0 770
âš™ï¸ 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 ofCallabletasks and returns a list ofFutureobjects.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
TheFuture 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