
thenCombine은 Java의 CompletableFuture(혹은 CompletionStage)에서 두 비동기 연산의 결과를 결합하는 메서드입니다. 요점만 정리하면 다음과 같습니다. - 목적: 두 CompletableFuture가 모두 완료되었을 때, 두 결과를 받아 하나의 값을 만들어내는 함수(BiFunction)를 적용하여 새로운 CompletableFuture를 반환합니다. - 시그니처(대표적):
CompletableFuture thenCombine(CompletionStage extends U> other, BiFunction super T,? super U,? extends V> fn) - 동작: - this와 other 두 Future가 모두 완료되면 fn이 호출되어 반환값으로 새 CompletableFuture가 완료됩니다. - 둘 중 하나가 예외(또는 취소)로 완료되면 결합 함수는 실행되지 않고 결과 Future도 예외(혹은 CancellationException)로 완료됩니다. - 함수 실행 시점: 기본 thenCombine(비동기 아님)은 두 Future 중 마지막으로 완료되는 쪽을 완료한 스레드(즉, 어떤 Future를 완성시킨 스레드)에서 fn을 실행할 수 있습니다. thenCombineAsync를 쓰면 별도의 Executor(지정하지 않으면 ForkJoinPool.commonPool())에서 실행됩니다. - 용도 구분: - thenCombine: 서로 독립적으로 실행되는 두 비동기 결과를 병합할 때 사용. - thenCompose: 첫 결과를 바탕으로 두 번째 비동기 작업을 시작해야 할 때(연속 호출, 플랫닝) 사용. - thenAcceptBoth / runAfterBoth: 결합은 하되 반환값이 필요 없는 경우 사용(thenAcceptBoth는 두 결과를 소비하고 Void 반환). - 간단한 예: CompletableFuture f1 = CompletableFuture.supplyAsync(() -> 2); CompletableFuture f2 = CompletableFuture.supplyAsync(() -> 3); CompletableFuture sum = f1.thenCombine(f2, (a, b) -> a + b); int result = sum.join(); // result == 5 요약하자면, thenCombine은 두 비동기 결과를 동시에 기다려 둘을 합성하는 연산을 제공하는 메서드입니다.