What is a Future in Java concurrency?

Java MCQ: What is a Future in Java concurrency?

a) A type of thread that executes tasks
b) A placeholder for a result that will be available in the future
c) A mechanism to run tasks in parallel
d) A new Java keyword for defining multithreaded tasks

Answer:

b) A placeholder for a result that will be available in the future

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

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top