We don't pass runnable or callable in completableFuture. It takes supplier type which is a functional interface. Just create normal methods and pass them with the object of executor. For reference conside the below example .
package completableFuture;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CompFuture {
ExecutorService firstExecService = Executors.newFixedThreadPool(5);
public static void main(String[] args) {
CompFuture compFuture = new CompFuture();
compFuture.testMe("Java");
}
public String m1(String param) {
Random r = new Random();
int val = r.nextInt(20) * 1000;
System.out.println(Thread.currentThread().getName() + " " + val);
try {
Thread.sleep(val);
} catch (InterruptedException e) {
e.printStackTrace();
}
return param + " Hello my";
}
public void m2(String salutation) {
System.out.println(Thread.currentThread().getName() + " ##" + salutation + " Friend!");
}
public void testMe(String start) {
System.out.println("TM: " + Thread.currentThread());
for (int i = 0; i < 5; i++) {
CompletableFuture.supplyAsync(() -> m1(start), firstExecService).thenAccept(s -> m2(s));
}
}
}
Output of above program:: Thread which takes min time to execute gives its output first.
TM: Thread[main,5,main]
pool-1-thread-1 1000
pool-1-thread-2 14000
pool-1-thread-4 3000
pool-1-thread-3 0
pool-1-thread-5 9000
pool-1-thread-3 ##Java Hello my Friend!
pool-1-thread-1 ##Java Hello my Friend!
pool-1-thread-4 ##Java Hello my Friend!
pool-1-thread-5 ##Java Hello my Friend!
pool-1-thread-2 ##Java Hello my Friend!
CompletableFuture
”— interesting mix of “want” and “need”. Doesn’t sound like a rational decision to me… – Relegate