I have written a small program to test the CompletableFuture behavior and I am not clear how the threads are created and used in execution of the tasks.
package com.my.testprog.concurrjava;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CompFuture {
ExecutorService firstExecService = Executors.newFixedThreadPool(2);
ExecutorService secondExecService = Executors.newFixedThreadPool(2);
public CompFuture() {
}
public String returnSalutation(String param) {
System.out.println("RS: " + Thread.currentThread());
return param + " Hello my";
}
public void returnGreetings(String salutation) {
System.out.println("RG: " + Thread.currentThread());
System.out.println("RG: " + salutation + " Friend!");
}
public void testMe(String start) {
System.out.println("TM: " + Thread.currentThread());
CompletableFuture.supplyAsync(() -> returnSalutation(start), firstExecService)
.thenAccept(s -> returnGreetings(s));
}
public static void main(String[] args) {
CompFuture compFuture = new CompFuture();
compFuture.testMe("Java");
compFuture.firstExecService.shutdown();
compFuture.secondExecService.shutdown();
}
}
When I run the program, it prints the following output:
TM: Thread[main,5,main]
RS: Thread[pool-1-thread-1,5,main]
RG: Thread[main,5,main]
RG: Java Hello my Friend!
My understanding is that it would use the same thread to invoke 'supplyAsync' and 'thenAccept' methods. However, above result indicating that only 'supplyAsync' is being executed in a separate thread, where as 'thenAccept' is run in main thread.
Can someone please elaborate?