티스토리 뷰

배경

CompletableFuture 에서 whenComplete 랑 whenCompleteAsync 의 차이가 어떤건지 궁금해서 기록

 

whenComplete: Returns a new CompletionStage with the same result or exception as this stage, that executes the given action when this stage completes.

 

whenCompleteAsync

Returns a new CompletionStage with the same result or exception as this stage, that executes the given action using this stage's default asynchronous execution facility when this stage completes.

 

테스트 - whenComplete

    @Test
    public void test_supplyAsync_whenComplete() throws InterruptedException {

        CompletableFuture future = CompletableFuture.supplyAsync(() -> {

            System.out.println("on supplyAsync: " + Thread.currentThread().getName());
            return "ret";
        }).whenComplete((s, throwable) -> {
            System.out.println("on whenComplete: " + Thread.currentThread().getName());
            System.out.println(s);
        });

        for (int i = 0; i < 100; i++) {
            Thread.sleep(1L);
        }
        System.out.println("outside: " + Thread.currentThread().getName());
    }
on supplyAsync: ForkJoinPool.commonPool-worker-3
on whenComplete: ForkJoinPool.commonPool-worker-3
ret
outside: main

테스트 - whenCompleteAsync

    @Test
    public void test_supplyAsync_with_whenCompleteAsync() throws InterruptedException {
        CompletableFuture future = CompletableFuture.supplyAsync(() -> {
            System.out.println("on supplyAsync: " + Thread.currentThread().getName());
            return "ret";
        }).whenCompleteAsync((s, throwable) -> {
            System.out.println("on whenCompleteAsync: " + Thread.currentThread().getName());
            System.out.println(s);
        });

        for (int i = 0; i < 100; i++) {
            Thread.sleep(1L);
        }
        System.out.println("outside: " + Thread.currentThread().getName());
    }
on supplyAsync: ForkJoinPool.commonPool-worker-3
on whenCompleteAsync: ForkJoinPool.commonPool-worker-5
ret
outside: main

이해한 결론

publish 를 async 로 한 뒤에 (결과를) subscribe 할 때에 비동기로 처리하기 위함으로 추정된다.

기타

reactor에서 publishOn 은 이해했는데 subscribeOn 은 한동안 이해를 못한채로 남아있었다.

같은 맥락이라면 왜 있는지 짐작이 갈 것 같다. 

 

 

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/12   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
글 보관함