PHpullh
학습 라이브러리/Java/ExecutorService & ThreadPool

JAVA · 비동기/동시성

ExecutorService & ThreadPool

스레드 풀로 자원을 효율적으로 관리하고 병렬 처리를 구현합니다.

비동기/동시성중급ExecutorServiceThreadPoolFutureScheduledExecutorServiceForkJoinPool

핵심 설명

스레드 풀로 자원을 효율적으로 관리하고 병렬 처리를 구현합니다.

Java code

import java.util.concurrent.*;
import java.util.*;

public class ThreadPoolDemo {
    public static void main(String[] args) throws Exception {

        // FixedThreadPool — 고정 크기 스레드 풀
        ExecutorService fixed =
            Executors.newFixedThreadPool(4);

        List<Future<String>> futures = new ArrayList<>();
        for (int i = 0; i < 8; i++) {
            final int id = i;
            futures.add(fixed.submit(() -> {
                Thread.sleep(100);
                return "task-" + id + " by " +
                    Thread.currentThread().getName();
            }));
        }

        for (Future<String> f : futures) {
            System.out.println(f.get()); // 블로킹 대기
        }
        fixed.shutdown();

        // ScheduledExecutorService — 예약 실행
        ScheduledExecutorService scheduler =
            Executors.newScheduledThreadPool(2);

        scheduler.schedule(
            () -> System.out.println("1초 후 실행"),
            1, TimeUnit.SECONDS);

        scheduler.scheduleAtFixedRate(
            () -> System.out.println("2초마다 실행: " + new Date()),
            0, 2, TimeUnit.SECONDS);

        Thread.sleep(6000);
        scheduler.shutdown();

        // ForkJoinPool — 분할정복 병렬 처리
        var pool = ForkJoinPool.commonPool();
        int[] arr = java.util.stream.IntStream.range(0, 1000).toArray();
        int sum = pool.submit(() ->
            java.util.Arrays.stream(arr).parallel().sum()
        ).get();
        System.out.println("병렬 합계: " + sum);
    }
}

학습 팁

Executors.newCachedThreadPool()은 스레드 수 제한이 없습니다. 갑자기 부하가 증가하면 수천 개의 스레드가 생성되어 OOM이 발생할 수 있습니다. 프로덕션에서는 newFixedThreadPool()이나 ThreadPoolExecutor로 직접 설정하세요.

주의할 점

fixed.shutdown()awaitTermination()을 호출하지 않으면 실행 중인 작업이 완료되기 전에 프로그램이 종료될 수 있습니다.

자주 묻는 질문

ExecutorService & ThreadPool란 무엇인가요?

스레드 풀로 자원을 효율적으로 관리하고 병렬 처리를 구현합니다.

ExecutorService & ThreadPool 학습 시 주의할 점은 무엇인가요?

fixed.shutdown() 후 awaitTermination() 을 호출하지 않으면 실행 중인 작업이 완료되기 전에 프로그램이 종료될 수 있습니다.