티스토리 뷰
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
Guide To CompletableFuture | Baeldung
Quick and practical guide to Java 8's CompletableFuture.
www.baeldung.com
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html
CompletableFuture (Java Platform SE 8 )
Returns a new CompletionStage with the same result or exception as this stage, that executes the given action when this stage completes. When this stage is complete, the given action is invoked with the result (or null if none) and the exception (or null i
docs.oracle.com
https://codechacha.com/ko/java-completable-future/
Java - CompletableFuture 사용 방법
CompletableFuture는 Future와 CompletionStage를 구현한 클래스입니다. Future이지만 supplyAsync(), runAsync()를 이용하여 직접 쓰레드를 생성하지 않고 async로 작업을 처리할 수 있습니다. 그리고 여러 CompletableFut
codechacha.com