バッチ処理用のスレッドプールを実装する
複数のドキュメントを同時に処理する必要がある、ドキュメント処理システムを開発していると想像してください。各ドキュメントには負荷の高い処理が必要で、並列で実行する必要があります。ただし、システムの過負荷を防ぐため、同時に実行する処理の数は制限したいとします。ここでは ExecutorService を使って、処理の負荷を効率的に管理する仕組みを実装します。
この演習はコースの一部です
Java におけるコードの最適化
演習の手順
- 3 つのスレッドを含む固定サイズのスレッドプールを作成します。
processDocument(doc)メソッドをタスクとしてエグゼキューターに送信します。- 即座に強制終了せずに、エグゼキューターをシャットダウンします。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
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";
}
}