🔹ExecutorService
- 병렬 작업을 쉽게 처리하기 위해 제공되는 Java 라이브러리
- ThreadPool을 사용하여 스레드를 효율적으로 관리
- 작업(Task)은 Queue에 저장되며, 실행 가능한 스레드가 순차적으로 처리
사용방법
1. ThreadPoolExecutor는 인터페이스 ExecutorService를 구현하여 사용가능하다.
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue)
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory)
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
RejectedExecutionHandler handler)
- corePoolSize : 기본적으로 유지할 스레드 개수
- maximumPoolSize : 최대 스레드 개수
- keepAliveTime : 유휴 스레드가 종료되기 전 대기 시간
- workQueue : 대기 중인 작업을 저장하는 큐
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadPoolExecutor.html
ThreadPoolExecutor (Java Platform SE 8 )
An ExecutorService that executes each submitted task using one of possibly several pooled threads, normally configured using Executors factory methods. Thread pools address two different problems: they usually provide improved performance when executing la
docs.oracle.com
2. 정적 팩토리 메소드 사용하여 구현
ExecutorService executorService = Executors.newCachedThreadPool();
ExecutorService executorService = Executors.newFixedThreadPool(int nThreads);
ExecutorService executorService = Executors.newSingleThreadExecutor();
CachedThreadPool
- 필요할 때마다 새로운 스레드를 생성 (60초 동안 Idle 상태면 제거)
- 단점: 스레드 수 제한이 없어 삭제되는 스레드보다 생성되는 스레드가 더 많아지면 스레드의 개수가 폭발적으로 증가 가능
FixedThreadPool
- 고정된 개수의 스레드를 유지
- 초과 작업은 큐에 저장되어 순차적으로 실행
SingleThreadExecutor
- 단일 스레드만 사용 (작업을 순차적으로 실행)
- 한 번에 하나씩 작업을 처리해야 할 때 유용
Task할당을 위한 메서드
execute(Runnable task) | 리턴값이 없으며, 작업 실패 여부를 확인할 수 없음 |
submit(Callable<T> task) | Future<T>를 반환하여 결과 확인 가능 |
invokeAny(Collection<Callable<T>> tasks) | 여러 개의 작업 중 가장 먼저 완료된 작업의 결과를 반환 |
invokeAll(Collection<Callable<T>> tasks) | 모든 작업이 완료될 때까지 기다리고, 결과 목록(List<Future<T>>) 반환 |
종료 메서드
shutdown() | 현재 실행 중인 작업이 끝나면 Executor 종료 |
shutdownNow() | 즉시 실행 중인 작업을 종료하려고 시도 |
awaitTermination(time, unit) | 모든 작업이 종료될 때까지 대기 |
🔹CountDownLatch
- 여러 개의 비동기 작업이 완료될 때까지 대기하도록 도와주는 Java 라이브러리
- countDown()을 호출하여 카운트를 감소시키고, 카운트가 0이 되면 대기 중인 스레드가 실행
🔹ExecutorService와 CountDownLatch를 사용한 예제 코드
public test() throws InterruptedException {
// 3개의 스레드를 가지는 스레드 풀 생성
ExecutorService executorService = Executors.newFixedThreadPool(3);
// CountDownLatch 생성
CountDownLatch latch = new CountDownLatch(3);
for (int i = 0; i < 3; i++) {
executorService.submit(() -> {
try {
// 작업 코드 생략
} catch (InterruptedException e) {
System.out.println("Exception occurred: " + e.getMessage());
} finally {
// 작업이 끝날 때마다 CountDownLatch의 카운트 감소
latch.countDown();
}
});
}
// 모든 스레드가 작업을 끝낼 때까지 대기
latch.await();
// ExecutorService 종료
executorService.shutdown();
}
'Spring' 카테고리의 다른 글
[Spring] 비동기 처리: @Async, @EnableAsync (0) | 2025.03.12 |
---|---|
[Spring] @Async와 프록시 객체 (0) | 2025.03.12 |
페이지네이션(Pagination) - 오프셋 기반, 커서 기반, Slice vs Page (0) | 2025.02.27 |
[SpringBoot] OpenAI API 적용하기 (0) | 2024.08.07 |
[Spring Security] 카카오 소셜 로그인 적용하기 (0) | 2024.07.08 |