[JAVA] Future, CompletableFuture

호호빵·2024년 7월 10일
0

Future

  • 자바 5부터 도입된 비동기 작업의 결과를 나타내는 객체
  • ExecutorService.submit() 같은 걸로 비동기 작업을 실행하면, 그 결과로 Future 객체가 리턴됨
  • 단점
    • 결과를 얻으려면 future.get()을 블로킹해서 기다려야 함
    • 작업이 끝났는지 알기 위해 isDone()을 계속 확인해야 함.
    • 콜백 등록이 안 됨 → 작업 완료 후 자동으로 뭔가를 실행하는 기능이 없음
ExecutorService executor = Executors.newSingleThreadExecutor();

Future<String> future = executor.submit(() -> {
    Thread.sleep(2000); // 2초 기다리기
    return "커피 완성!";
});

System.out.println("커피 주문 완료! 기다리는 중...");

String result = future.get(); // ⚠️ 여기가 블로킹. 2초 동안 멈춤.
System.out.println(result);   // 출력: 커피 완성!

executor.shutdown();
  • future.get()이 작업이 끝날 때까지 기다려야 함
  • 기다리는 동안 다른 작업 못 함.

CompletableFuture

  • 자바 8부터 등장한 업그레이드 버전 Future
  • 특징
    • 비동기 실행 및 콜백 지원
    • 결과 조합 (thenCombine, thenApply, thenAccept 등)
    • 예외 처리 용이 (exceptionally, handle 등)
    • 멀티스레딩 쉽게 처리 가능

// 비동기 + 콜백
CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> {
    try {
        Thread.sleep(2000); // 2초 대기
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return "커피 완성!";
});

System.out.println("커피 주문 완료! 기다리는 동안 다른 일 하기...");

cf.thenAccept(result -> {
    System.out.println("✅ 받은 메시지: " + result); // 출력: 커피 완성!
});

System.out.println("👉 다른 일 수행 중...");

// cf가 끝날 때까지 메인 쓰레드가 너무 빨리 끝나지 않도록 잠깐 대기
Thread.sleep(3000);


// 출력
// 커피 주문 완료! 기다리는 동안 다른 일 하기...
// 👉 다른 일 수행 중...
// ✅ 받은 메시지: 커피 완성!

Reference

https://devfunny.tistory.com/809
https://rudaks.tistory.com/entry/Future%EC%99%80-CompletableFuture#google_vignette

profile
하루에 한 개념씩

0개의 댓글