0

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?

Naman
  • 27,789
  • 26
  • 218
  • 353
AnilJ
  • 1,951
  • 2
  • 33
  • 60
  • I would not have expected it to use the same thread, but one from either the same executor or from the default ForkJoinPool. – daniu Feb 10 '19 at 07:38
  • 1
    See [this answer](https://stackoverflow.com/a/47711550/2711488) and [that answer](https://stackoverflow.com/a/46062939/2711488). – Holger Feb 10 '19 at 11:09

0 Answers0