| 특징 | Runnable | Callable |
|---|---|---|
| 메서드 이름 | run() |
call() |
| 반환값 | 없음 (void) |
있음 (제네릭 사용 가능) |
| 예외 처리 가능 여부 | 불가능 | 가능 (throws Exception) |
Future 사용 가능 여부 |
불가능 | 가능 |
언제 사용???
RunnableCallable둘 다 비동기 작업을 처리하는 인터페이스이지만, CompletableFuture는 Future의 기능을 확장한 더 강력한 API이다.
단점
get()이 블로킹됨)
get()을 호출하면 작업이 끝날 때까지 메인 스레드가 대기Future를 조합할 수 없음
Future끼리 연결해서 사용하는 기능이 없음import java.util.concurrent.*;
public class FutureExample {
public static void main(String[] args) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(() -> {
Thread.sleep(2000);
});
try {
String result = future.get(); // 결과를 기다려야 함 (블로킹)
System.out.println(result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
executor.shutdown();
}
}
CompletableFuture는 Future의 단점을 보완하여 비동기 작업을 더욱 유연하게 처리할 수 있다.
CompletableFuture의 장점