> For the complete documentation index, see [llms.txt](https://notes.tejpratapsingh.com/_/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://notes.tejpratapsingh.com/_/java-tips/concurrency/completable-future/example-of-completable-future.md).

# 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));
```
