> For the complete documentation index, see [llms.txt](https://www.pranaypourkar.co.in/the-programmers-guide/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.pranaypourkar.co.in/the-programmers-guide/java/java-concepts/concurrency-and-multithreading/asynchronous-programming/future.md).

# Future

## About

The `Future` interface in Java, introduced in Java 5, is part of the `java.util.concurrent` package and represents the result of an asynchronous computation. It provides methods to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation. If necessary, the computation can also be canceled using the `Future` interface.

## **Asynchronous Computation**

* `Future` represents the result of a computation that may not have completed yet.
* This allows to start a task in a separate thread and continue executing other code while the task runs.

## **Methods in `Future` Interface**

**`get()`**:

* Retrieves the result of the computation, blocking if necessary until the computation is complete.
* If the computation completed successfully, `get()` returns the result.
* If the computation threw an exception, `get()` throws an `ExecutionException`, which wraps the original exception.
* If the thread is interrupted while waiting, `get()` throws an `InterruptedException`.

**`get(long timeout, TimeUnit unit)`**:

* Retrieves the result, but only waits for the specified timeout.
* If the computation is not complete within the timeout, it throws a `TimeoutException`.

**`cancel(boolean mayInterruptIfRunning)`**:

* Attempts to cancel the execution of the task.
* The parameter `mayInterruptIfRunning` determines whether the thread executing the task should be interrupted.
* Returns `true` if the task was canceled before it completed, `false` if it could not be canceled (e.g., because it had already completed).

**`isCancelled()`**:

* Returns `true` if the task was canceled before it completed normally.

**`isDone()`**:

* Returns `true` if the task has completed (either successfully, with an exception, or via cancellation).

## Example

```java
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 FutureExample {

    public static void main(String[] args) {
        ExecutorService executor = Executors.newSingleThreadExecutor();

        Callable<String> callableTask = () -> {
            Thread.sleep(2000);
            return "Task's Execution";
        };

        Future<String> future = executor.submit(callableTask);

        // Perform some other operations

        try {
            // Blocking call to get the result
            String result = future.get();
            System.out.println("Result: " + result);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        } finally {
            executor.shutdown();
        }
    }
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://www.pranaypourkar.co.in/the-programmers-guide/java/java-concepts/concurrency-and-multithreading/asynchronous-programming/future.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
