2017-10-05 3 views
-3

나는 이와 같은 것을 달성하려고 노력하고있다. 이것은 의도를 표현한 구성 예입니다.루프에서 completable future를 호출하고 모든 결과를 결합하는 방법은 무엇입니까?

모든 완료 가능한 미래를 실행하고 모든 결과를 하나의 결과로 결합하여 반환해야합니다. 따라서 아래 예제에서 컬렉션 allResults는 "one", "two", "three"라는 문자열을 각각 3 번 가져야합니다. 나는 그들 모두가 연속적이지 않고 평행하게 달리고 싶다.

완성 할 수있는 미래에 어떤 API를 사용했는지 알려주는 포인터는 매우 유용합니다. 그 이전 작업의 결과를 기다리는 동안 당신도 다른 작업을 시작하지 않는 의미로

public class Main { 


    public static void main(String[] args) { 

     int x = 3; 
     List<String> allResuts; 

     for (int i = 0; i < x; i++) { 

      //call getCompletableFutureResult() and combine all the results 
     } 

    } 

    public static CompletableFuture<List<String>> getCompletableFutureResult() { 

     return CompletableFuture.supplyAsync(() -> getResult()); 
    } 

    private static List<String> getResult() { 


     List<String> list = new ArrayList<>(); 
     list.add("one"); 
     list.add("two"); 
     list.add("three"); 

     return list; 
    } 


} 
+0

_combine_을 정의하십시오. –

답변

1

당신은 1 for 루프에서 결과를 수집 할 수 없습니다.

모든 작업이 시작되면 결과를 수집하기 시작하십시오.

public static void main(String[] args) throws Exception 
{ 
    int x = 3; 

    Queue<CompletableFuture<List<String>>> cfs = new ArrayDeque<>(x); 
    for (int i = 0; i < x; i++) 
    { 
    cfs.add(getCompletableFutureResult()); 
    } 

    List<String> allResuts = new ArrayList<>(); 
    for (CompletableFuture<List<String>> cf : cfs) 
    allResuts.addAll(cf.get()); 

    System.out.println(allResuts); 
} 
1

Venkata Raju의 답변에 문제가 있습니다. Raju는 을 사용하여 전화를받습니다.이 호출은 차단 호출이며 비동기 스타일의 코딩 목적을 없앱니다. 항상 선물을 피하십시오.

은 약

CompletableFuture.allOf 방법은 여러 선물을 처리 할 때 사용하기위한 것입니다 등 thenApply, thenAccept, thenCompose, thenCombine 같은 미래 가치를 처리하는 빌드 방법 내장의 톤이있다.

그것은이 다음 서명을

public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs) 

사이드 노트가 있습니다 만 완료하는 최초의 미래에 대해 걱정하는 경우CompletableFuture.anyOf 사용할 수 있습니다. 모든 선물을 완료해야 할 때 allOf을 사용하십시오.

CompletableFuture.allOf를 사용하여 다음과 같이 스펙을 코딩합니다.

public class DorjeeTest { 


    public static CompletableFuture<List<String>> getCompetableFutureResult() { 
     return CompletableFuture.supplyAsync(() -> getResult()); 
    } 
    public static List<String> getResult() { 
     return Lists.newArrayList("one", "two", "three"); 
    } 

    public static void testFutures() { 
     int x = 3; 
     List<CompletableFuture<List<String>>> futureResultList = Lists.newArrayList(); 
     for (int i = 0; i < x; i++) { 
      futureResultList.add(getCompetableFutureResult()); 
     } 

     CompletableFuture[] futureResultArray = futureResultList.toArray(new CompletableFuture[futureResultList.size()]); 

     CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(futureResultArray); 

     CompletableFuture<List<List<String>>> finalResults = combinedFuture 
       .thenApply(voidd -> 
         futureResultList.stream() 
           .map(future -> future.join()) 
         .collect(Collectors.toList())); 

     finalResults.thenAccept(result -> System.out.println(result)); 
    } 


    public static void main(String[] args) { 
     testFutures(); 
     System.out.println("put debug break point on this line..."); 

    } 
}