1. 概要

ExecutorService フレームワークを使用すると、複数のスレッドでタスクを簡単に処理できます。 スレッドが実行を終了するのを待ついくつかのシナリオを例示します。

また、 ExecutorService を正常にシャットダウンし、すでに実行中のスレッドが実行を終了するのを待つ方法を示します。

2. エグゼキュータのシャットダウン後

Executor、を使用する場合、 shutdown()または shutdownNow()メソッドを呼び出すことでシャットダウンできます。 ただし、すべてのスレッドの実行が停止するまで待機しません。

awaitTermination()メソッドを使用すると、既存のスレッドの実行が完了するのを待つことができます。

これにより、すべてのタスクが実行を完了するか、指定されたタイムアウトに達するまで、スレッドがブロックされます。

public void awaitTerminationAfterShutdown(ExecutorService threadPool) {
    threadPool.shutdown();
    try {
        if (!threadPool.awaitTermination(60, TimeUnit.SECONDS)) {
            threadPool.shutdownNow();
        }
    } catch (InterruptedException ex) {
        threadPool.shutdownNow();
        Thread.currentThread().interrupt();
    }
}

3. CountDownLatchを使用する

次に、この問題を解決するための別のアプローチを見てみましょう。 CountDownLatch を使用して、タスクの完了を通知します。

await()メソッドを呼び出したすべてのスレッドに通知される前に、デクリメントできる回数を表す値で初期化できます。

たとえば、現在のスレッドが別の N スレッドの実行を終了するのを待つ必要がある場合、Nを使用してラッチを初期化できます。

ExecutorService WORKER_THREAD_POOL 
  = Executors.newFixedThreadPool(10);
CountDownLatch latch = new CountDownLatch(2);
for (int i = 0; i < 2; i++) {
    WORKER_THREAD_POOL.submit(() -> {
        try {
            // ...
            latch.countDown();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    });
}

// wait for the latch to be decremented by the two remaining threads
latch.await();

4. Using invokeAll()

スレッドを実行するために使用できる最初のアプローチは、 invokeAll()メソッドです。 このメソッドは、すべてのタスクが終了するか、タイムアウトが期限切れになると、Futureオブジェクトのリストを返します

また、返される Future オブジェクトの順序は、提供されているCallableオブジェクトのリストと同じであることに注意する必要があります。

ExecutorService WORKER_THREAD_POOL = Executors.newFixedThreadPool(10);

List<Callable<String>> callables = Arrays.asList(
  new DelayedCallable("fast thread", 100), 
  new DelayedCallable("slow thread", 3000));

long startProcessingTime = System.currentTimeMillis();
List<Future<String>> futures = WORKER_THREAD_POOL.invokeAll(callables);

awaitTerminationAfterShutdown(WORKER_THREAD_POOL);

long totalProcessingTime = System.currentTimeMillis() - startProcessingTime;
 
assertTrue(totalProcessingTime >= 3000);

String firstThreadResponse = futures.get(0).get();
 
assertTrue("fast thread".equals(firstThreadResponse));

String secondThreadResponse = futures.get(1).get();
assertTrue("slow thread".equals(secondThreadResponse));

5. ExecutorCompletionServiceを使用する

複数のスレッドを実行する別のアプローチは、ExecutorCompletionServiceを使用することです。提供されているExecutorServiceを使用してタスクを実行します。

invokeAll()との違いの1つは、実行されたタスクを表す Futures、が返される順序です。 ExecutorCompletionServiceはキューを使用して、結果を終了した順序で保存します。一方、 invokeAll()は、指定されたタスクリストのイテレーターによって生成されたものと同じ順序のリストを返します。

CompletionService<String> service
  = new ExecutorCompletionService<>(WORKER_THREAD_POOL);

List<Callable<String>> callables = Arrays.asList(
  new DelayedCallable("fast thread", 100), 
  new DelayedCallable("slow thread", 3000));

for (Callable<String> callable : callables) {
    service.submit(callable);
}

結果には、 take()メソッドを使用してアクセスできます。

long startProcessingTime = System.currentTimeMillis();

Future<String> future = service.take();
String firstThreadResponse = future.get();
long totalProcessingTime
  = System.currentTimeMillis() - startProcessingTime;

assertTrue("First response should be from the fast thread", 
  "fast thread".equals(firstThreadResponse));
assertTrue(totalProcessingTime >= 100
  && totalProcessingTime < 1000);
LOG.debug("Thread finished after: " + totalProcessingTime
  + " milliseconds");

future = service.take();
String secondThreadResponse = future.get();
totalProcessingTime
  = System.currentTimeMillis() - startProcessingTime;

assertTrue(
  "Last response should be from the slow thread", 
  "slow thread".equals(secondThreadResponse));
assertTrue(
  totalProcessingTime >= 3000
  && totalProcessingTime < 4000);
LOG.debug("Thread finished after: " + totalProcessingTime
  + " milliseconds");

awaitTerminationAfterShutdown(WORKER_THREAD_POOL);

6. 結論

ユースケースに応じて、スレッドが実行を終了するのを待つさまざまなオプションがあります。

CountDownLatch は、他のスレッドによって実行された一連の操作が終了したことを1つ以上のスレッドに通知するメカニズムが必要な場合に役立ちます。

ExecutorCompletionService は、タスクの結果にできるだけ早くアクセスする必要がある場合や、実行中のすべてのタスクが終了するのを待つ必要がある場合に役立ちます。

この記事のソースコードは、GitHubから入手できます。