MyCallable("B")
次のサンプルコードがあり、他のコードが1秒より速く実行される場合、実行に1秒以上かかるとしましょう。したがって、を呼び出すループ内で、Future.get()
をスローしTimeoutException
ます。
public static void main(String[] args) {
ExecutorService es = Executors.newFixedThreadPool(2);
List<Future<String>> futures = new ArrayList<Future<String>>();
futures.add(es.submit(new MyCallable("A")));
futures.add(es.submit(new MyCallable("B")));
futures.add(es.submit(new MyCallable("C")));
futures.add(es.submit(new MyCallable("D")));
futures.add(es.submit(new MyCallable("E")));
try {
for(Future<String> f : futures) {
try {
System.out.println("result " + f.get(1, TimeUnit.SECONDS));
}
catch (TimeoutException e) {
// how do I know which MyCallable() has timed out?
} catch (ExecutionException e) {
System.out.println(e.getMessage());
}
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
finally {
es.shutdown();
}
}
予想どおり、各MyCallable()インスタンスは実行されますが、タイムアウトしたインスタンスについては、エラー処理を実行したいと思います。これには、どれがどのCallable
に関連付けられているかを知る必要がありFuture
ます。
この関連付けのメカニズムはありますか、それともそのメソッドCallable
内のすべてのエラー処理を処理するのは私次第ですか?call()