배치 처리를 위한 스레드 풀 구현
여러 문서를 동시에 처리해야 하는 문서 처리 시스템을 개발한다고 가정해 봅시다. 각 문서는 연산량이 많아 병렬로 처리해야 하지만, 시스템 과부하를 막기 위해 동시 작업 수에는 제한을 두고 싶습니다. 이 연습에서는 ExecutorService를 사용해 처리 작업을 효율적으로 관리하는 솔루션을 구현하겠습니다.
이 연습은 강의의 일부입니다
Java 코드 최적화
연습 안내
- 스레드 3개로 구성된 고정 스레드 풀을 생성하세요.
processDocument(doc)메서드를 executor에 태스크로 제출하세요.- 즉시 강제 종료하지 않고 executor를 정상적으로 종료(shutdown)하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
public class DocumentProcessor {
public static void main(String[] args) throws InterruptedException {
List documents = List.of("Doc1", "Doc2", "Doc3", "Doc4", "Doc5");
List> futures = new ArrayList<>();
// Create a fixed thread pool with 3 threads
ExecutorService executor = Executors.____(____);
for (String doc : documents) {
// Submit the processDocument() method to the executor
futures.add(executor.submit(() -> ____(____)));
}
// Shutdown the executor and wait for termination
executor.____();
executor.awaitTermination(10, TimeUnit.SECONDS);
try {
for (Future future : futures) {
System.out.println(future.get());
}
} catch (ExecutionException e) {
System.out.println("Error processing documents: " + e.getMessage());
}
}
private static String processDocument(String docId) throws InterruptedException {
System.out.println("Processing " + docId + " on thread " + Thread.currentThread().getName());
Thread.sleep((long) (Math.random() * 1000));
return docId + " Processed";
}
}