javamultithreadingfuturevavrvavr-test

vavr's Future don't execute some code, with method andThen


In this code, I have two methods using vavr library. From this library I am using Future with the method andThen, this method run when the future has been completed, and this is synchronous, but when the thread call to the method "printTime" in this method, all program stop, and the test is success. this is the method

    public void printTime(String m){
    String pattern = "HH:mm:ss:SSS";
    SimpleDateFormat formato = new SimpleDateFormat(pattern);
    Date date = new Date();
    String dateString = formato.format(date);
    String retorno = dateString+" "+m;
    System.out.println(retorno);
}

and this is the test

    @Test
public void futuroAndThen() {
    Future<String> f1 = Future.of(()->"Julian");
    Future<String> f2 = Future.of(()->"Carvajal");
    Future<String> f3 = Future.of(()->"Montoya");

    Future<String> fResult = f3.andThen(x-> {
        System.out.println(x.get());
        System.out.println(Thread.currentThread().getName());
        printTime("andThen2"+Thread.currentThread().getName());
    }).andThen(y->{
        System.out.println("y:"+y.get());
        System.out.println(Thread.currentThread().getName());
        f2.andThen(x->{
            System.out.println("f2: "+x.get());
            System.out.println("thread f2 "+Thread.currentThread().getName());
        });
        printTime("andThen2"+Thread.currentThread().getName());
    });

}

finally the result within method printTime is:

Montoya
pool-1-thread-3
y:Montoya
pool-1-thread-1
f2: Carvajal
thread f2 pool-1-thread-3

and with the method is:

Montoya
pool-1-thread-1

but some moments the console is empty.

thank you very much :)


Solution

  • Your test finishes and the main JUnit runner thread exits the JVM before the Future could finish. This is why you get inconsistent results on the console, it all depends on the timing of the execution of the Futures, which - as of vavr 0.9.2 - happen in a cached thread pool.

    If you want to synchronously wait for the Future to be completed, you can use

    fResult = fResult.await();
    

    at the end of your test. Then your test will wait for the Future instances to finish, and your output will be:

    Montoya
    pool-1-thread-4
    23:56:59:570 andThen2pool-1-thread-4
    y:Montoya
    pool-1-thread-3
    f2: Carvajal
    thread f2 pool-1-thread-4
    23:56:59:572 andThen2pool-1-thread-3