バッチ処理のためのスレッドプールを実装する
複数のドキュメントを同時に処理するドキュメント処理システムを開発しているとします。各ドキュメントは計算量の大きい処理が必要で、並列に実行したい一方で、同時実行数を制限してシステムの過負荷を防ぎたい状況です。ここでは ExecutorService を使って、処理負荷を効率的に管理するソリューションを実装します。
この演習はコースの一部です
Javaコード最適化
演習の手順
- 3 本のスレッドを含む固定スレッドプールを作成します。
processDocument(doc)メソッドをタスクとして executor に送信します。- すぐに強制終了はせず、executor をシャットダウンします。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
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";
}
}