What is Callable and Future in Java?

In Java, Callable and Future are interfaces that are part of the java.util.concurrent package, allowing for asynchronous programming. Callable is similar to Runnable but can return a result and throw checked exceptions. Future represents the result of an asynchronous computation, allowing you to retrieve the result once it's available.

Callable Interface

The Callable interface is a functional interface that can be used to make tasks that return a value. It has a single method called call(). Here is a simple example:

import java.util.concurrent.Callable; public class MyCallable implements Callable { @Override public String call() throws Exception { return "Task executed successfully!"; } }

Future Interface

The Future interface represents the result of an asynchronous computation. It provides methods for checking if the computation is complete, waiting for its completion, and retrieving the result. Here's an example of using Callable with Future:

import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; public class FutureExample { public static void main(String[] args) throws Exception { ExecutorService executor = Executors.newFixedThreadPool(1); Future future = executor.submit(new MyCallable()); // Do other tasks... // Get the result of the computation String result = future.get(); System.out.println(result); executor.shutdown(); } }

Callable Future Java Asynchronous Programming Concurrency ExecutorService