# Example of completable future

In below example, we&#x20;

```java
new CompletableFuture<Integer>().thenApplyAsync(new Function<Integer, String>() {
    @Override
    public String apply(Integer integer) {
        // Do some heavy task here
        return "Something returned from long task";
    }
}, Executors.newSingleThreadExecutor()).thenAcceptAsync(new Consumer<String>() {
    @Override
    public void accept(String s) {
        // Do something with result of previous task
    }
}).thenRunAsync(new Runnable() {
    @Override
    public void run() {
        // Do something after everything ends
    }
});
```

Here is another example in Android, how you can do some operation in background thread and return back to main thread when everything is completed.

```java
new CompletableFuture<Integer>()
        .thenApplyAsync(integer -> "Something returned from long task", Executors.newSingleThreadExecutor())
        .thenAcceptAsync(s -> {
            System.out.println("Previous result on main thread: " + s);
        }, ContextCompat.getMainExecutor(context));
```


---

# Agent Instructions: Querying This Documentation

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

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://notes.tejpratapsingh.com/_/java-tips/concurrency/completable-future/example-of-completable-future.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
