ExecutorService and Callable
×


ExecutorService and Callable

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 a Future.
  • invokeAll() โ€“ Executes a collection of Callable tasks and returns a list of Future 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

FeatureRunnableCallable
Return ValueNoYes
Exception HandlingCannot throw checked exceptionsCan throw checked exceptions
Methodrun()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!



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat