Future is an interface in Java that represents the outcome of a task executed asynchronously. It acts as a placeholder for a result that may not be available immediately, allowing the main thread to continue processing while the task runs in the background. Once the task finishes, the result can be retrieved from the Future object.
Key Points: • Future is commonly used with ExecutorService to execute tasks asynchronously. • It provides methods such as get(), isDone(), isCancelled(), and cancel() to manage task execution. • Calling get() blocks the current thread until the task completes and the result becomes available.
Example: In an e-commerce application, generating a sales report may take several seconds. Instead of blocking the main application thread, the report generation can run asynchronously, and a Future object can be used to retrieve the report once processing is complete.
Code Example:
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class FutureExample {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
Callable<String> task = () -> {
Thread.sleep(2000);
return "Report Generated";
};
Future<String> future = executor.submit(task);
System.out.println("Processing other tasks...");
String result = future.get();
System.out.println(result);
executor.shutdown();
}
}Interview Tip: A concise interview answer is: Future is an interface that represents the result of an asynchronous computation. It allows checking task status, waiting for completion, retrieving the result, or cancelling the task when used with ExecutorService.