truthsayer
truthsayer

Reputation: 429

How do I run CompletableFuture on a new thread in parallel

So I have this code that I want to run on new thread.

Let me explain better, I have 2 methods in which I want to run in parallel.

public String method1(){
   ExecutorService pool = Executors.newSingleThreadExecutor();

   return CompletableFuture.supplyAsync(() -> {
            //...
        }, pool);
} 


public String method2(){
   ExecutorService pool = Executors.newSingleThreadExecutor();

   return CompletableFuture.supplyAsync(() -> {
            //...
        }, pool);
} 

So I would like to call these two methods in another method & Run them in parallel.

public void method3(){
 // Run both methods
 method1();
 method2();
 // end
}

Upvotes: 1

Views: 1324

Answers (1)

hoaz
hoaz

Reputation: 10143

You method signature does not correspond to return value. When you change both methods to return CompletableFuture you can define expected behavior in method3:

CompletableFuture<String> method1Future = method1();
CompletableFuture<String> method2Future = method2();

// example of expected behavior
method1Future.thenCombine(method2Future, (s1, s2) -> s1 + s2);

In the example above you will concatenate strings which are supplied asynchronously by method1 and method2 when both futures are completed.

Upvotes: 1

Related Questions