Java CompletableFuture의 실행기 선택과 타임아웃 처리
이 글의 목차
비동기 작업을 어디서 실행할지는 ExecutorService를 명시해 정하고, 작업 결과는 CompletableFuture로 연결한다. Java 21에서 같은 주문을 플랫폼 스레드와 가상 스레드로 처리해도 영수증 금액은 23000 KRW로 같다. 별도 예제에서는 join()에서 발생한 예외의 원인이 TimeoutException이어도 제출한 작업은 끝까지 실행될 수 있음을 확인한다. Java 21 CompletableFuture API · Java 21 ExecutorService API
메서드 선택표
| 메서드 | 쓰는 경우 | 실무 예 |
|---|---|---|
supplyAsync / runAsync |
작업을 비동기로 제출한다. 전자는 값, 후자는 Void 완료를 돌려준다. |
주문 조회 / 캐시 갱신 |
thenApply |
성공 값을 새 값으로 바꾼다. | 주문 객체에서 ID 추출 |
thenCompose |
성공 값으로 다음 비동기 작업을 시작하고 그 결과까지 연결한다. | 주문 요약을 받아 영수증 발급 |
thenCombine |
이미 시작한 두 단계가 모두 성공하면 결과를 합친다. | 상품값과 배송비 합산 |
thenAccept / thenRun |
성공 뒤 부수효과를 실행한다. 전자에만 성공 값이 전달된다. | ID를 감사 로그에 남김 / 처리 완료 카운터 증가 |
allOf |
모든 단계가 끝날 때 완료된다. 하나라도 실패하면 예외 완료되며, 개별 값은 모으지 않는다. | 영수증과 감사 로그가 모두 끝날 때까지 대기 |
whenComplete / exceptionally / handle |
성공·실패 관찰 / 실패만 복구 / 성공과 실패 모두 변환 | 실패 로그 / 계약된 기본 배송비 / 상태 응답 |
orTimeout / completeOnTimeout |
기한까지 미완료면 같은 Future를 예외 또는 기본값으로 완료한다. | 기한 초과 오류 / 선택 항목의 기본 표시 |
같은 작업을 두 실행기에 제출하기
JDK 21이 필요하다. 두 작업을 각각 supplyAsync에 제출하므로 주문 조회와 배송비 조회는 서로를 기다리지 않고 진행할 수 있다. 첫 실행기는 플랫폼 스레드 두 개를 재사용하고, 둘째 실행기는 제출된 작업마다 가상 스레드를 만든다. 두 실행기 모두 try-with-resources로 열며 close()는 정상 종료를 시작하고 작업이 끝날 때까지 기다린다. Java 21 Executors API · Java 21 ExecutorService API
그림은 주문 합성 경로를 보여준다. 주문에서 thenApply로 ID를 꺼내 thenAccept로 감사 로그를 남기는 동안, thenCombine은 배송비까지 받아 합계를 만든다. thenCompose는 그 합계로 같은 실행기에 영수증 작업을 제출하고 완료를 연결한다. allOf(receipt, audit).join()이 성공한 뒤 receipt.join()은 이미 완료된 값을 꺼낸다. 그림 다음에 실행하는 단일 작업 submit/get과 타임아웃 실습은 코드에서 확인할 수 있다.
FutureExample.java
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class FutureExample {
record Order(int id, int price) {}
record Summary(int orderId, int total) {}
public static void main(String[] args) throws Exception {
try (var pool = Executors.newFixedThreadPool(
2, Thread.ofPlatform().name("platform-", 0).factory())) {
demo("platform", pool);
}
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
demo("virtual", executor);
}
}
static void demo(String name, ExecutorService executor) throws Exception {
System.out.println("[" + name + "]");
var order = CompletableFuture.supplyAsync(
() -> {
blockingStep("order");
return new Order(42, 20_000);
}, executor);
var shipping = CompletableFuture.supplyAsync(
() -> {
blockingStep("shipping");
return 3_000;
}, executor);
var summary = order.thenCombine(shipping,
(o, fee) -> new Summary(o.id(), o.price() + fee));
var receipt = summary.thenCompose(s -> CompletableFuture.supplyAsync(
() -> {
blockingStep("receipt");
return "order %d: %d KRW".formatted(s.orderId(), s.total());
}, executor));
var audit = order.thenApply(Order::id)
.thenAccept(id -> System.out.println("audit: " + id));
CompletableFuture.allOf(receipt, audit).join();
System.out.println(receipt.join());
var probe = executor.submit(() -> Thread.currentThread().isVirtual());
System.out.println("submit/get: " + probe.get());
// 완료시키는 작업이 없는 Future로 대기 시간 초과만 재현한다.
String fallback = new CompletableFuture<String>()
.completeOnTimeout("fallback", 30, TimeUnit.MILLISECONDS)
.join();
System.out.println("timeout: " + fallback);
}
static void blockingStep(String task) {
System.out.printf("%s virtual=%s%n",
task, Thread.currentThread().isVirtual());
try {
Thread.sleep(30); // I/O 대기를 흉내 낸다.
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new CompletionException(e);
}
}
}
실패 관찰, 복구, 시간 초과
whenComplete는 실패를 기록하고 콜백이 정상 반환하면 원래 결과를 전달한다. 이 예에서 실패는 그대로 이어져 exceptionally가 3000을 돌려준다. handle은 복구된 단계 대신 원래 실패 단계에 연결해 unavailable로 바꾼다. 실제 과금에 쓰는 배송비는 명시된 계약이 있을 때만 대체값을 사용한다.
첫 예제에서 completeOnTimeout은 30ms가 지나면 대기 중인 Future를 fallback으로 정상 완료한다. 둘째 예제에서 제출한 작업은 orTimeout이 Future를 TimeoutException으로 완료할 때까지 래치에서 기다린다. 래치가 열리면 작업은 끝나고, 이미 타임아웃된 Future의 complete는 false를 반환한다. HTTP나 DB 작업의 기한과 취소는 그 작업을 맡은 클라이언트나 드라이버에서 설정한다. 타임아웃 예제는 작업 시작을 확인한 뒤 기한을 설정한다. Java 21 CompletableFuture API
FutureFailureExample.java
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class FutureFailureExample {
public static void main(String[] args) throws Exception {
var failed = CompletableFuture.<Integer>failedFuture(
new IllegalStateException("shipping unavailable"));
int recovered = failed
.whenComplete((value, error) ->
System.out.println("failed: " + (error != null)))
.exceptionally(error -> 3_000)
.join();
System.out.println("recovered: " + recovered);
String status = failed.handle((value, error) ->
error == null ? "ok: " + value : "unavailable").join();
System.out.println(status);
var started = new CountDownLatch(1);
var release = new CountDownLatch(1);
var result = new CompletableFuture<String>();
try (var executor = Executors.newSingleThreadExecutor()) {
var task = executor.submit(() -> {
started.countDown();
release.await();
return result.complete("finished");
});
try {
started.await();
result.orTimeout(30, TimeUnit.MILLISECONDS).join();
} catch (CompletionException e) {
System.out.println(e.getCause().getClass().getSimpleName());
} finally {
release.countDown();
}
System.out.println("task finished, late value accepted: " + task.get());
}
}
}
실행과 결과
두 파일을 같은 디렉터리에 저장하고 실행한다.
javac --release 21 FutureExample.java FutureFailureExample.java
java FutureExample
java FutureFailureExample
다음은 Zulu OpenJDK 21.0.1에서 컴파일 후 실제로 실행한 출력 한 회분이다.
[platform]
order virtual=false
shipping virtual=false
audit: 42
receipt virtual=false
order 42: 23000 KRW
submit/get: false
timeout: fallback
[virtual]
order virtual=true
shipping virtual=true
audit: 42
receipt virtual=true
order 42: 23000 KRW
submit/get: true
timeout: fallback
failed: true
recovered: 3000
unavailable
TimeoutException
task finished, late value accepted: false
의도한 결과는 각 실행에서 order, shipping, receipt가 플랫폼 스레드이면 virtual=false, 가상 스레드이면 virtual=true를 표시하고, 같은 23000 KRW 영수증을 출력하는 것이다. 독립 작업과 감사 로그의 출력 순서는 실행마다 달라질 수 있다. submit은 단일 작업의 Future를 반환하고 get은 값을 기다려 꺼낸다. 여기서는 그 한 작업의 isVirtual() 결과도 확인한다.
후속 단계의 실행 스레드와 대기
- 일반
CompletableFuture의thenApplyAsync같은 비동기 메서드에서 실행기를 생략하면 앞 단계에 넘긴 실행기를 물려받지 않는다. 기본값은ForkJoinPool.commonPool()이며 공용 풀의 병렬도가 2 미만이면 작업마다 새 스레드를 만든다. 하위 클래스는 인스턴스 비동기 메서드의 기본 실행기를defaultExecutor()로 바꿀 수 있다. 실행 위치를 정해야 하면 실행기를 명시한다. thenApply나thenCombine처럼Async가 없는 후속 계산의 스레드는 고정되지 않는다. 현재 Future를 완료한 스레드나 완료 메서드를 호출하는 다른 스레드에서 실행될 수 있다. 이미 완료된 단계에 후속 계산을 붙일 때 등록하는 스레드에서 바로 실행될 수도 있다.- 결과가 아직 없으면
join()과get()모두 대기할 수 있다. 예제의 일반 실패에서join()은 비검사CompletionException을,get()은 검사ExecutionException을 던진다.get()은 대기 중 인터럽트를InterruptedException으로 알리며get(timeout, unit)으로 호출자의 대기 시간에 한도를 둘 수 있다. Java 21 CompletableFuture API Thread.sleep(30)은 I/O 대기를 흉내 낸다. 이 예제는 성능을 측정하지 않는다. 가상 스레드는 대기 중인 작업을 많이 유지할 수 있게 해도 DB 연결 수나 외부 서비스의 동시 요청 한도를 늘려 주지 않는다. OpenJDK JEP 444 · 가상 스레드와 DB 연결 제한
댓글