[Spring] Callable, Runnable, Future

SangDosa·2024년 8월 19일

Spring

목록 보기
9/10

정의

Spring의 비동기 처리를 위한 인터페이스들

Callable

call() 메서드를 통해서 작업을 실행하며 결과를 반환할 수 있고, 체크 예외를 처리할 수 있음

Runnable

run() 메서드를 통해 작업을 실행하며 결과를 반환값이 없다.

Future

  • 비동기 작업의 결과를 나타내며, 작업이 완료될 때까지 기다리거나 작업이 완료되었는지 확인할 수 있는 메서드를 제공
  • 대부분 Callable과 함께 사용됨

사용 메소드

  1. submit
public class FutureExample {
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Callable<String> callable = new MyCallable();
        
        // callable에 대한 call()을 실행시킴
        Future<String> future = executor.submit(callable);
        
        // 다른 작업을 수행할 수 있음
        System.out.println("Doing other tasks...");
        
        // 비동기 작업의 결과를 기다림
        String result = future.get();
        System.out.println("Callable result: " + result);
        
        executor.shutdown();
    }
}
  1. invokeAll
public class InvokeAllExample {
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newFixedThreadPool(3);

        List<Callable<String>> tasks = Arrays.asList(
            () -> {
                TimeUnit.SECONDS.sleep(2);
                return "Task 1";
            },
            () -> {
                TimeUnit.SECONDS.sleep(1);
                return "Task 2";
            },
            () -> {
                TimeUnit.SECONDS.sleep(3);
                return "Task 3";
            }
        );
        
		// Callable안에 있는 모든 값들이 한번에 실행됨
        List<Future<String>> futures = executor.invokeAll(tasks);

        for (Future<String> future : futures) {
            // 비동기 작업의 결과를 기다림
            String result = future.get();
            System.out.println("Result: " + result);
        }

        executor.shutdown();
    }
}
profile
조용한 개발자

0개의 댓글