JAVA · 비동기/동시성
Future와 Callable
Callable로 결과를 반환하는 비동기 작업과 Future의 한계를 이해합니다.
비동기/동시성중급FutureCallable비동기get
핵심 설명
Callable로 결과를 반환하는 비동기 작업과 Future의 한계를 이해합니다.
Java code
import java.util.concurrent.*;
public class FutureCallable {
// Callable — 결과 반환 + 예외 던지기 가능
static class PriceCalculator implements Callable<Double> {
private final String product;
PriceCalculator(String product) { this.product = product; }
@Override
public Double call() throws Exception {
Thread.sleep(1000); // 외부 API 호출 시뮬레이션
return Math.random() * 100;
}
}
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(3);
try {
Future<Double> future = executor.submit(
new PriceCalculator("노트북"));
// 결과 대기 전 다른 작업 가능
System.out.println("가격 조회 중...");
System.out.println("취소됨? " + future.isCancelled());
System.out.println("완료됨? " + future.isDone());
// get() — 블로킹 대기
Double price = future.get(5, TimeUnit.SECONDS);
System.out.printf("가격: %.2f%n", price);
// 취소
Future<Double> cancelable = executor.submit(
new PriceCalculator("키보드"));
cancelable.cancel(true); // 인터럽트로 취소
} finally {
executor.shutdown();
}
}
}학습 팁
Future.get()에 타임아웃을 항상 지정하세요. 무한 대기를 방지합니다. 논블로킹이 필요하면 CompletableFuture를 사용하세요.
주의할 점
Future.get()은 블로킹 호출입니다. 여러 Future를 순차적으로 get()하면 병렬 효과가 사라집니다.
자주 묻는 질문
Future와 Callable란 무엇인가요?
Callable 로 결과를 반환하는 비동기 작업과 Future 의 한계를 이해합니다.
Future와 Callable 학습 시 주의할 점은 무엇인가요?
Future.get() 은 블로킹 호출입니다. 여러 Future를 순차적으로 get() 하면 병렬 효과가 사라집니다.
Continue Learning
Java 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.