티스토리 뷰
IO가 오래걸리는 작업(db 또는 타 서비스 호출)에 CompletableFuture를 이용하면 쉽게 병렬 처리를 할 수 있습니다.
물론 db의 connection pool, 타 서비스 호출 시에 해당 서비스에서 감당할 수 있는 정도를 확인하고 상황에 맞게 동시 실행 Thread 개수를 지정합니다.
List<CompletableFuture<String>> completableFutures = new ArrayList<>();
ExecutorService executorService = Executors.newFixedThreadPool(100);
IntStream.rangeClosed(1, 100)
.forEach(i -> {
CompletableFuture<String> completableFuture =
CompletableFuture.supplyAsync(() -> {
String threadName = Thread.currentThread().getName();
System.out.println("task start - " + threadName);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return i + " - " + threadName;
}, executorService);
completableFutures.add(completableFuture);
});
CompletableFuture<String>[] cfs =
(CompletableFuture<String>[]) completableFutures.toArray(new CompletableFuture[completableFutures.size()]);
CompletableFuture.allOf(cfs)
.thenApply(v -> completableFutures.stream()
.map(CompletableFuture::join)
.collect(toList())
);
List<String> collect = Arrays.stream(cfs)
.map(CompletableFuture::join)
.collect(toList());
System.out.println(collect.size());
CompletableFuture를 잘 사용해서 동시성 프로그램을 작성해보세요
참고
https://www.baeldung.com/java-completablefuture
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html
https://codechacha.com/ko/java-completable-future/
반응형
댓글