Java Callable and Future: Master Asynchronous Programming 🎯

beginner
18 min

Java Callable and Future: Master Asynchronous Programming 🎯

Welcome to our comprehensive guide on Java Callable and Future! In this tutorial, we'll learn how to use these powerful tools to perform asynchronous tasks in Java. Let's dive in!

What are Callable and Future in Java? 📝

Callable and Future are part of the ExecutorService in Java. They help us run long-running tasks asynchronously and handle the results when they're ready.

Callable

Callable is an interface that extends Runnable, providing a call() method to execute a task. It returns a result of any type, which can be any Java object.

java
import java.util.concurrent.*; public class MyCallable implements Callable<Integer> { private int number; public MyCallable(int number) { this.number = number; } @Override public Integer call() throws Exception { // Perform long-running task here Thread.sleep(5000); return number * number; } }

Future

Future is a class that represents the result of an asynchronous computation. It can be used to check the status of the computation, wait for its completion, and retrieve the result.

java
Future<Integer> future = executor.submit(new MyCallable(5));

Using Callable and Future Together 💡

To use Callable and Future together, you first create a Callable object, then submit it to an ExecutorService to run asynchronously. After that, you can use the Future object to check the status of the computation, wait for its completion, and retrieve the result.

java
import java.util.concurrent.*; public class Main { public static void main(String[] args) throws Exception { ExecutorService executor = Executors.newSingleThreadExecutor(); Callable<Integer> callable = new MyCallable(5); Future<Integer> future = executor.submit(callable); System.out.println("Main thread continues execution..."); // Get the result of the computation Integer result = future.get(); System.out.println("The square of 5 is: " + result); executor.shutdown(); } }

Advanced Usage ✅

You can also use Futures to handle exceptions that may occur during the execution of a Callable task.

java
import java.util.concurrent.*; public class MyCallableException extends Callable<Integer> { private int number; public MyCallableException(int number) { this.number = number; } @Override public Integer call() throws Exception { // Perform long-running task here Thread.sleep(5000); if (number == 4) { throw new Exception("An error occurred with number 4"); } return number * number; } } public class Main { public static void main(String[] args) throws Exception { ExecutorService executor = Executors.newSingleThreadExecutor(); Callable<Integer> callable = new MyCallableException(4); Future<Integer> future = executor.submit(callable); try { // Get the result of the computation Integer result = future.get(); System.out.println("The square of 4 is: " + result); } catch (ExecutionException e) { Throwable cause = e.getCause(); System.out.println("An error occurred: " + cause.getMessage()); } executor.shutdown(); } }

Quiz 💡

Quick Quiz
Question 1 of 1

What does Callable provide in Java?

Quick Quiz
Question 1 of 1

What does Future represent in Java?