I have the following example code and let's say that MyCallable("B")
takes longer than one second to execute, when the others execute quicker than one second. Therefore inside my loop that calls Future.get()
, it will throw a 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();
}
}
As expected each of the MyCallable() instances execute, but for the one that times out I would like to perform some error handling and this requires knowing which Callable
is associated with which Future
.
Is there a mechanism for this association or is it up to my Callable
to handle all the error processing inside it's call()
method?