0

CompletableFuture으로 재귀를 구현해야하는 상황이 있습니다. CompletableFuture 중 하나가 결과를 반환 할 때마다 recursionFuture(ex)으로 전화하고 싶지만 어떻게 구현해야할지 모르겠습니다. 현재 상황에서는 future1future2이 출력을 반환하고 조건을 검사하는 경우에만 recursionFuture(ex)이 호출됩니다. 어떤 도움을 주시면 감사하겠습니다.출력을 기다리지 않고 CompletableFuture를 어떻게 처리합니까?

public static void recursionFuture(ExecutorService ex) 
    { 
     try 
     { 
      CompletableFuture<Object> future1 = CompletableFuture.supplyAsync(() -> new ConcurrencyPoC_CompletableFuture().executeTask(), ex); 
      CompletableFuture<Object> future2 = CompletableFuture.supplyAsync(() -> new ConcurrencyPoC_CompletableFuture().executeTask(), ex); 

      if (future1.get() != null | future2.get() != null) 
      { 
       System.out.println("Future1: " + future1.get() + " Future2: " + future2.get()); 
       recursionFuture(ex); 
      } 
     } 
     catch(Exception e) 
     { 
      e.printStackTrace(); 
     } 
    } 

답변

1

당신은 그것을 달성하기 위해 thenRun()anyOf()을 결합 할 수 있습니다. 두 가지 선물 모두에 get()으로 전화하지 마십시오. 프로그램이 완료 될 때까지 기다릴 수 있기 때문입니다. isDone()을 사용하여 미래가 완료되었는지 확인한 후 get()으로 전화하십시오.

CompletableFuture<Object> future1 = CompletableFuture.supplyAsync(() -> new ConcurrencyPoC_CompletableFuture().executeTask(), ex); 
CompletableFuture<Object> future2 = CompletableFuture.supplyAsync(() -> new ConcurrencyPoC_CompletableFuture().executeTask(), ex); 

CompletableFuture.anyOf(future1, future2).thenRun(() -> { 
    if (future1.isDone()) { 
     System.out.println("Future 1: " + future1.get()); 
    } 
    if (future2.isDone()) { 
     System.out.println("Future 2: " + future2.get()); 
    } 
    recursionFuture(ex); 
}); 

anyOf() 즉시 제공되는 선물 중 하나가 완료로 완료하는 새로운 미래를 만들 것입니다. thenRun()은 나중에 호출 된 이후에 주어진 Runnable을 실행합니다.

+0

감사합니다 앤드류,이 작동하지만 작은 문제가 있습니다. 재귀로 인해 executeTask()가 아무 것도 반환하지 않고 무한정 지속되는 경우에도 코드는 계속됩니다. futire1.get()! = null과 같은 미래의 출력을 검사 할 수 있습니까? 그렇다면 앞에서 설명한 문제가 발생하면서 재귀 호출을 호출하십시오. 여기 제발 조언 해 줄래? –

+0

글쎄, 난 같은 코드를 편집하여이 작업을 얻었다 : CompletableFuture.anyOf (future1, future2) .thenRunAsync (() -> \t \t \t { \t \t \t \t recursionFuture (예) \t \t \t} \t \t \t \t \t, 예); –

0

두 개의 CompletableFutures 만 사용하는 경우 runAfterEither/runAfterEitherAsync를 살펴볼 수도 있습니다. acceptEither/acceptEitherAsync와 같이 반환 된 값에 액세스 할 수있는 버전도 있습니다.