🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Introduction
The Callable interface and the Future interface in Java are part of the java.util.concurrent package and provide a powerful way to handle asynchronous programming. Callable is similar to Runnable, but it can return a result and throw a checked exception. The Future interface represents the result of an asynchronous computation and provides methods to check if the computation is complete, to wait for its completion, and to retrieve the result.
Table of Contents
- Introduction to Callable
- Introduction to Future
- Using Callable and Future with ExecutorService
- Example: Basic Callable and Future
- Example: Handling Exceptions with Callable and Future
- Example: Cancelling a Future Task
- Conclusion
1. Introduction to Callable
The Callable interface is a functional interface that is similar to Runnable, but it can return a result and throw a checked exception. It has a single method, call.
Syntax:
public interface Callable<V> {
V call() throws Exception;
}
2. Introduction to Future
The Future interface represents the result of an asynchronous computation. It provides methods to check if the computation is complete, to wait for its completion, and to retrieve the result.
Key Methods:
boolean cancel(boolean mayInterruptIfRunning): Attempts to cancel the execution of the task.boolean isCancelled(): Returnstrueif the task was cancelled before it completed normally.boolean isDone(): Returnstrueif the task completed.V get() throws InterruptedException, ExecutionException: Waits if necessary for the task to complete and then retrieves its result.V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException: Waits if necessary for at most the given time for the task to complete and then retrieves its result.
3. Using Callable and Future with ExecutorService
The ExecutorService interface provides methods to manage termination and methods that can produce a Future for tracking progress of one or more asynchronous tasks.
Submitting a Callable Task:
Future<V> submit(Callable<V> task): Submits aCallabletask for execution and returns aFuturerepresenting the pending results of the task.
4. Example: Basic Callable and Future
Let's create an example to demonstrate how to use Callable and Future.
Example:
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
class MyCallable implements Callable<Integer> {
@Override
public Integer call() throws Exception {
// Simulate long-running task
Thread.sleep(2000);
return 123;
}
}
public class CallableFutureExample {
public static void main(String[] args) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(new MyCallable());
System.out.println("Task submitted.");
try {
// Wait for the result
Integer result = future.get();
System.out.println("Task completed with result: " + result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
} finally {
executor.shutdown();
}
}
}
Output:
Task submitted.
Task completed with result: 123
Explanation:
- The
MyCallableclass implements theCallableinterface and returns anInteger. - The
CallableFutureExampleclass creates anExecutorServicewith a single thread. - A
MyCallabletask is submitted to the executor, returning aFutureobject. - The
getmethod is used to wait for the task to complete and retrieve the result.
5. Example: Handling Exceptions with Callable and Future
When using the get method, it can throw an ExecutionException if the task throws an exception during its execution.
Example:
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
class MyCallableWithException implements Callable<Integer> {
@Override
public Integer call() throws Exception {
throw new Exception("An error occurred during task execution.");
}
}
public class FutureExceptionHandlingExample {
public static void main(String[] args) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(new MyCallableWithException());
System.out.println("Task submitted.");
try {
// Wait for the result
Integer result = future.get();
System.out.println("Task completed with result: " + result);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
System.out.println("Task failed with exception: " + e.getCause());
} finally {
executor.shutdown();
}
}
}
Output:
Task submitted.
Task failed with exception: java.lang.Exception: An error occurred during task execution.
Explanation:
- The
MyCallableWithExceptionclass throws an exception during task execution. - The
FutureExceptionHandlingExampleclass submits the task to the executor. - The
getmethod throws anExecutionExceptionbecause the task failed. - The cause of the exception is printed using
e.getCause().
6. Example: Cancelling a Future Task
This example demonstrates how to cancel a task using the cancel method of the Future interface.
Example:
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
class MyCallable implements Callable<Integer> {
@Override
public Integer call() throws Exception {
// Simulate long-running task
Thread.sleep(5000);
return 123;
}
}
public class FutureCancelExample {
public static void main(String[] args) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(new MyCallable());
System.out.println("Task submitted.");
try {
// Wait for the result with timeout
Integer result = future.get(2, TimeUnit.SECONDS);
System.out.println("Task completed with result: " + result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
System.out.println("Task timed out. Cancelling...");
future.cancel(true);
} finally {
executor.shutdown();
}
if (future.isCancelled()) {
System.out.println("Task was cancelled.");
} else if (future.isDone()) {
System.out.println("Task completed.");
}
}
}
Output:
Task submitted.
Task timed out. Cancelling...
Task was cancelled.
Explanation:
- The
MyCallableclass simulates a long-running task. - The
FutureCancelExampleclass submits the task to the executor. - The
getmethod with a timeout is used to wait for the task to complete. - If the task times out, it is cancelled using the
cancelmethod. - The
isCancelledandisDonemethods are used to check the task's status.
7. Conclusion
The Callable and Future interfaces in Java provide a robust mechanism for handling asynchronous tasks. The Callable interface allows tasks to return a result and throw exceptions, while the Future interface provides methods to manage and retrieve the results of asynchronous computations. By using these interfaces with an ExecutorService, you can efficiently manage and control the execution of concurrent tasks in your applications.
Happy coding!
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment