What is Callable and Future in Java: Simple Explanation and Example
Callable is a Java interface that represents a task that returns a result and can throw exceptions. Future represents the result of an asynchronous computation, allowing you to check if the task is done and get its result when ready.How It Works
Imagine you ask a friend to bake a cake while you do other things. You get a ticket (like a receipt) that you can use later to check if the cake is ready and to pick it up. In Java, Callable is like the baking task you give to your friend. It defines what work needs to be done and can return a result when finished.
The Future is like the ticket you receive. It lets you check if the task is done, wait for it if needed, and get the final result. This way, your program can keep running other code without waiting for the task to finish immediately.
Example
This example shows how to use Callable to create a task that returns a number after a delay, and Future to get the result asynchronously.
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; public class CallableFutureExample { public static void main(String[] args) { ExecutorService executor = Executors.newSingleThreadExecutor(); Callable<Integer> task = () -> { try { Thread.sleep(2000); // Simulate long task } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } return 42; }; Future<Integer> future = executor.submit(task); System.out.println("Task submitted, doing other work..."); try { Integer result = future.get(); // Waits if needed System.out.println("Result from Callable: " + result); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } executor.shutdown(); } }
When to Use
Use Callable and Future when you want to run tasks in the background and get their results later without blocking your main program. This is helpful for tasks like fetching data from the internet, processing large files, or running calculations that take time.
For example, a web server can handle multiple requests simultaneously by submitting tasks with Callable and using Future to get results when ready, improving responsiveness.
Key Points
- Callable can return a result and throw checked exceptions.
- Future represents the pending result of a
CallableorRunnabletask. - You can check if the task is done, cancel it, or wait for the result using
Future. - They help run tasks asynchronously, improving program efficiency.