6
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Threadの戻り値と例外

Last updated at Posted at 2015-05-07

JavaのThread実行で...

  • 実行した処理の戻り値の取得
  • 発生した例外の取得

が簡単にできましたので、忘れないうちにメモ.

Integer retVal = null;

// Thread実行したい処理を、Callable<T> interfaceで指定.
// ※ lambda (java8) が使える.
ExecutorService service = Executors.newSingleThreadExecutor();
Future<Integer> future = service.submit( () -> 1 + 2 );

try {
    // 戻り値を取得する.
    // Threadの終了、もしくはタイムアウトまで待つ.
    retVal = future.get(2, TimeUnit.SECONDS);

} catch (InterruptedException ex) {
    // Threadが中断された.

} catch (ExecutionException ex) {
    // 実行した処理が例外を投げた.
    Throwable cause = ex.getCause();

} catch (TimeoutException ex) {
    // タイムアウト秒に達した.
    future.cancel(true); // threadをinterruptする.
}

service.shutdown();
System.out.println("result: " + retVal);
result: 3

タイムアウトをするには、Thread実行する処理を適切に実装する必要がある.

// Thread実行したい処理を、Callable<T> interfaceで指定.
// ※ lambda (java8) が使える.
ExecutorService service = Executors.newSingleThreadExecutor();
Future<Integer> future = service.submit( () -> {
    // 時間のかかる処理.
    for (int i = 0; i < 1000000; i++) {
        // future.cancel(true) でThreadがinterruptされる.
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }

        System.out.println("cnt: " + i);
    }

    return 1 + 2;
});
6
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?