Java MCQ: What is a Future in Java concurrency?
Answer:
Explanation:
A Future
in Java concurrency is a placeholder for a result that will be available at some point in the future. It is part of the java.util.concurrent
package and represents the result of an asynchronous computation. A Future
object allows you to check if the computation is complete, wait for it to complete, and retrieve the result when it is available.
Here’s an example of using a Future
:
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.newFixedThreadPool(2);
Callable<String> task = () -> {
Thread.sleep(2000);
return "Task completed";
};
Future<String> future = executor.submit(task);
System.out.println("Task result: " + future.get());
executor.shutdown();
}
}
In this example, a Callable
task is submitted to an ExecutorService
, and a Future
object is returned. The get()
method of the Future
object is used to retrieve the result of the task, which will be available once the task is complete. The Future
interface also provides methods such as isDone()
to check if the task is finished and cancel()
to attempt to cancel the task.
The Future
interface is an essential part of Java’s concurrency model, providing a way to handle asynchronous tasks and retrieve their results in a non-blocking manner.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html