Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a value using CompletableFuture

I created an example, i want to know how can I return a value using the CompletableFuture ? I also changed the CompletableFuture<Void> exeFutureList to be CompletableFuture<Integer> exeFutureList but eclipse always suggest to set it back to Void.

Please let me know how to return value using CompletableFuture.

Code:

    public class MainClass {

    static ExecutorService exe = null;
    static CompletableFuture<Void> exeFutureList = null;

    public static void main(String[] args) {
        exe = Executors.newFixedThreadPool(1);
        exeFutureList = CompletableFuture.runAsync(new RunClass(8), exe);
    }

    static class RunClass implements Runnable {

        private int num;

        public RunClass(int num) {
            // TODO Auto-generated constructor stub
            this.num = num;
        }

        public void run() {
            // TODO Auto-generated method stub
            this.num = this.num + 10;
        }

    }
}
like image 390
user2121 Avatar asked May 23 '15 14:05

user2121


People also ask

What does CompletableFuture return?

toCompletableFuture() is an instance method of the CompletableFuture class. It is used to return the same completable future upon which this method is invoked.

How do you use Executorservice with CompletableFuture?

The above code block shows how we can use the Executor in CompletableFuture. We create the Executor Service object at line 7 with thread pool as fixed thread pool with 2 as value. As a next step in line 20, we just simply provide it in the runAsync() method as a parameter of CompletableFuture class.

Can CompletableFuture be reused?

It was about a scenario where a method returns a CompletableFuture and it may return the same already completed future on each invocation, if that matches its semantic. That method would break, if someone uses one of the obtrude… methods on the returned future, but I wouldn't call that a real problem.

How do you end a Completable Future?

In Java, we use an instance method of the CompletableFuture class, cancel() , that attempts to cancel the execution of a task.


1 Answers

Runnable is just an interface with a run method that does not return anything.

Therefore the runAsync method that you are using returns a CompletableFuture<Void>

You need to submit a Supplier, using the supplyAsync method:

final int arg = 8;
CompletableFuture<Integer> f = CompletableFuture.supplyAsync(() -> {
    return arg + 10;
}, exe);

You can also create your own Supplier<Integer> implementation instead of using lambda.

like image 94
Jean Logeart Avatar answered Nov 15 '22 09:11

Jean Logeart