Programming/JAVA

자바 Future 인터페이스

khj1999 2024. 10. 22. 21:44

Java에서 Future 인터페이스는 비동기 작업의 결과를 나타내는 객체이다.
Future를 사용하면 실행 중인 작업의 상태를 확인하고, 작업이 완료되면 결과를 가져올 수 있다.
다음은 Future 타입에 대한 주요 내용이다.

1. 주요 메서드

Future 인터페이스에는 다음과 같은 주요 메서드가 있다:

  • boolean cancel(boolean mayInterruptIfRunning)
    • 작업을 취소합니다.
    • mayInterruptIfRunningtrue인 경우, 현재 실행 중인 작업을 중단할 수 있다.
  • boolean isCancelled()
    • 작업이 취소되었는지 여부를 반환한다.
  • boolean isDone()
    • 작업이 완료되었는지 여부를 반환한다.
  • V get() throws InterruptedException, ExecutionException
    • 작업의 결과를 반환한다. 작업이 완료되지 않은 경우 대기한다.
  • V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException
    • 지정된 시간 내에 작업의 결과를 반환한다. 시간 초과 시 TimeoutException을 발생시킨다.

2. 사용 예제

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class FutureExample {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(1);

        Callable<String> task = () -> {
            Thread.sleep(2000);
            return "작업 완료";
        };

        Future<String> future = executorService.submit(task);

        try {
            // 결과를 가져오고 대기
            String result = future.get();
            System.out.println(result);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        } finally {
            executorService.shutdown();
        }
    }
}

3. Future 사용 시 고려사항

  • Blocking Behavior: get() 메서드는 작업이 완료될 때까지 블록합니다.
    즉, 결과가 준비될 때까지 기다려야 한다.
  • Exception Handling: 작업이 예외를 발생시키면 get() 메서드는 ExecutionException을 발생시킴. 이 예외를 통해 실제 예외를 확인할 수 있습니다.
  • Cancellation: 작업이 취소되면 isCancelled() 메서드가 true를 반환하고, get() 호출 시 CancellationException이 발생할 수 있다.

결론

Future 타입은 비동기 작업의 결과를 나타내고, 작업의 상태를 관리하는 데 유용하다.
멀티스레딩 프로그래밍에서 비동기 작업의 결과를 효과적으로 처리하는 방법 중 하나임.