동시성 프로그래밍 및 자바 (3) - Callable과 Future

이동욱

2021/03/06

Categories: 프로그래밍 - 자바

Callable과 Future


Screen Shot 2021-03-06 at 3 56 51 PM

다음은 Future에 대해 설명한 API 주석이다.

get() - 결과를 가져오기


Screen Shot 2021-03-06 at 3 56 51 PM

get()은 오버로딩 된 두가지 메서드를 제공한다.

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 Main {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executorService = Executors.newSingleThreadExecutor();

        Callable<String> hello = () -> {
            Thread.sleep(2000L);
            return "Hello";
        };

        Future<String> helloFuture = executorService.submit(hello);
        System.out.println("Started!");

        helloFuture.get(); // blocking call

        System.out.println("End!!");
        executorService.shutdown();
    }
}

isDone(), isCancelled() - 작업 상태 확인하기


Screen Shot 2021-03-06 at 3 56 51 PM

cancel() - 작업 취소하기

작업 취소

invokeAll()과 invokeAny()의 차이점


invokeAll

invokeAll

import java.util.Arrays;
import java.util.List;
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 Main {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executorService = Executors.newSingleThreadExecutor();

        Callable<String> hello = () -> {
            Thread.sleep(2000L);
            return "Hello";
        };

        Callable<String> java = () -> {
            Thread.sleep(4000L);
            return "Java";
        };

        Callable<String> dongwook = () -> {
            Thread.sleep(100L);
            return "Dong Wook";
        };

        List<Future<String>> futures = executorService.invokeAll(Arrays.asList(hello, java, dongwook));

        for (Future<String> f : futures) {
            System.out.println(f.get()); // Hello, Java, Dong Wook 순서대로 출력된다.
        }
        executorService.shutdown();
    }
}

invokeAny

invokeAny

public class Main {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executorService = Executors.newFixedThreadPool(4);

        Callable<String> hello = () -> {
            Thread.sleep(2000L);
            return "Hello";
        };

        Callable<String> java = () -> {
            Thread.sleep(4000L);
            return "Java";
        };

        Callable<String> dongwook = () -> {
            Thread.sleep(100L);
            return "Dong Wook";
        };

        String futures = executorService.invokeAny(Arrays.asList(hello, java, dongwook));

        System.out.println(futures); // Dong Wook
        executorService.shutdown();
    }
}

참고 문헌

>> Home