Java8 : CompletableFuture get() method does not get fired/invoked

时间:2017-04-10 00:41:15

标签: java

I am writing a code to explore CompletableFuture in Java8, When I run the the attached code, It prints "Line 47" and stopped, It did not print the statement that I have in getRandomText() method, I am not sure if I am missing something !!!

* CompletableFutureTest *

public class CompletableFutureTest {

public static void main(String[] args) 
        throws InterruptedException,ExecutionException {

    List<CompletableFuture<FakeAPI1>> apis= 
            Arrays.asList(
                new CompletableFuture<FakeAPI1>(),
                new CompletableFuture<FakeAPI1>(),
                new CompletableFuture<FakeAPI1>()
            );

    Long start= System.currentTimeMillis();

    CompletableFuture<String> stringFuture=new CompletableFuture<String>();
    System.out.println("Line 42");
    List<String> list=apis.stream()
        .map(api->
                {
                    try{
                        System.out.println("Line 47");
                        String value =api.get().getRandomText();
                        System.out.println("Line 49");
                        stringFuture.complete(value);
                        System.out.println("Line 51");
                        return value;
                    }catch(ExecutionException e){
                       System.out.println("ExecutionException");
                    }catch(InterruptedException e){
                       System.out.println("InterruptedException");
                    }
                    return "NA";
                })
        .collect(Collectors.toList());
    System.out.println("Line 55");
    list.stream().forEach(System.out::println);

    Long end= System.currentTimeMillis();
    System.out.println("CompletableFutureTest took " + (end-start) + " ms" );
}
}

* FakeAPI1 *

public class FakeAPI1 implements FakeAPI{

@Override
public void consume(){
    try{
        Thread.sleep(1000L);
        System.out.println("Hello from FakeAPI1");
    }catch(InterruptedException e){
        System.out.println("Eat it silently");
    }
}

public String getRandomText(){
    System.out.println("getRandomText() @ FakeAPI1 was called ");
    try{
        Thread.sleep(1000L);
        return "Hello from FakeAPI1";
    }catch(InterruptedException e){
        System.out.println("Eat it silently");
    }
    return "Default message from FakeAPI1";
}
}

1 个答案:

答案 0 :(得分:0)

According to the Javadoc for CompletableFuture#get:

Waits if necessary for this future to complete, and then returns its result.

You need to actually assign a task to each CompletableFuture itself or it will hang indefinitely.

相关问题