Show wrong data using java 8 CompletableFuture

I wrote a simple example to understand CompletableFuture. But when I print it on console. Sometime It only show "asyn demo" This is my code

public class DemoAsyn extends Thread {
    public static void main(String[] args) {
        List<String> mailer = Arrays.asList("bach1@gmail.com", "bach2@gmail.com", "bach3@gmail.com", "bach4@gmail.com",
                "bach5@gmail.com");

        Supplier<List<String>> supplierMail = () -> mailer;
        Consumer<List<String>> consumerMail = Mail::notifyMessage;
        Function<List<String>,List<String>> funcMail = Mail::sendMessage;
        CompletableFuture.supplyAsync(supplierMail).thenApply(funcMail).thenAccept(consumerMail);
        System.out.println("asyn demo");
    }
}


public class Mail {

    public static List<String> sendMessage(List<String> notifies) {
        notifies.forEach(x -> System.out.println("sent to " + x.toString()));
        return notifies;
    }

    public static void notifyMessage(List<String> notifies) {
        notifies.forEach(x -> System.out.println("notified to " + x.toString()));
    }
}
Jon Skeet
people
quotationmark

You're starting the asynchronous operation, but you're not waiting for it to finish - when you've printed asyn demo there's nothing else keeping a non-daemon thread alive, so the process terminates. Just wait for the CompletableFuture<Void> returned by thenAccept to finish using get():

import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;

public class Test {
    public static void main(String[] args)
        throws InterruptedException, ExecutionException {
        List<String> mailer = Arrays.asList(
                "bach1@gmail.com", 
                "bach2@gmail.com",
                "bach3@gmail.com",
                "bach4@gmail.com",
                "bach5@gmail.com");

        Supplier<List<String>> supplierMail = () -> mailer;
        Consumer<List<String>> consumerMail = Test::notifyMessage;
        Function<List<String>,List<String>> funcMail = Test::sendMessage;
        CompletableFuture<Void> future = CompletableFuture
            .supplyAsync(supplierMail)
            .thenApply(funcMail)
            .thenAccept(consumerMail);
        System.out.println("async demo");
        future.get();
    }


    private static List<String> sendMessage(List<String> notifies) {
        notifies.forEach(x -> System.out.println("sent to " + x.toString()));
        return notifies;
    }

    private static void notifyMessage(List<String> notifies) {
        notifies.forEach(x -> System.out.println("notified to " + x.toString()));
    }
}

people

See more on this question at Stackoverflow