0

CompletableFuture is not working as expected when I am using I/O operation in supplyAsync/thenApply etc. methods

I am new to CompletableFuture, so I guess there is something that I am missing.

private static void completableTest() {
    CompletableFuture.supplyAsync(() -> {
        GET(); 
        writeToFile("sync");
        System.out.println("sync");
        return "";
    }).thenApply(t -> {
        GET(); 
        writeToFile("apply");
        System.out.println("apply");
        return "";
    }).thenAccept(t -> {
        writeToFile("accept");
        System.out.println("accept");
    });

GET() makes an httpGet call;

writeToFile() writes the content to file;

My file is also empty when I use GET() or replace it with Thread.sleep(). However it works fine if I don't use GET().

NOTE : It works fine when I use join() at the end. (File has the correct output).

Didier L
  • 18,905
  • 10
  • 61
  • 103
  • 1
    Possible duplicate of [CompletableFuture is not getting executed. If I use the ExecutorService pool its work as expected but not with the default forkJoin common pool](https://stackoverflow.com/questions/51879659/completablefuture-is-not-getting-executed-if-i-use-the-executorservice-pool-its) – Didier L Oct 04 '19 at 16:44
  • If you don't wait for the future chain to complete, how can you expect anything is actually done right after you defined it? – George Leung Oct 04 '19 at 16:44
  • 1
    @GeorgeLeung, you don't have to explicitly wait for the future chain to complete, but you must make sure that your program does not exit before. See my suggested duplicated target and also https://stackoverflow.com/questions/48573856/how-to-use-completablefuture-in-java-8-to-start-an-async-task-and-let-main-threa/48574331 – Didier L Oct 04 '19 at 16:47
  • @DidierL, before seeing your comment I made an edit specifying the time of observation, "right after you defined it". So I am not wrong. :D A little more explanation for OP: If your program exits right after you return, the callbacks may not have been executed and will not have the chance to be executed. – George Leung Oct 04 '19 at 16:50

0 Answers0