...
Compliant Solution (Future<V> and submit())
This compliant solution uses a Future object to catch any exception thrown by the task. It uses the invokes the ExecutorService.submit() method to submit the task so that a Future object can be obtained. It uses the Future object to let the task re-throw the exception so that it can be handled locally.
| Code Block | ||
|---|---|---|
| ||
final class PoolService {
private final ExecutorService pool = Executors.newFixedThreadPool(10);
public void doSomething() {
Future<?> future = pool.submit(new Task());
// ...
try {
future.get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // Reset interrupted status
} catch (ExecutionException e) {
Throwable exception = e.getCause();
// Forward to exception reporter
}
}
}
|
...