Executors and thread pools question 83 of 180 mid
What happens to an exception thrown inside a pooled task?
- It kills the pool
- Correct:
executereaches the uncaught handler;submithides it in theFutureuntil someone callsget() - It is always printed to stderr
- It is rethrown on the submitting thread
This asymmetry swallows more bugs than any other part of the API. execute(Runnable) lets the
exception propagate: the thread's UncaughtExceptionHandler runs (by default printing to stderr) and
ThreadPoolExecutor quietly replaces the dead worker.
submit wraps the task in a FutureTask, which catches everything and stores it. No log line, no
handler, nothing, until someone calls get() and receives an ExecutionException. A fire-and-forget
submit whose Future is discarded loses failures completely.
Defences: wrap task bodies in try/catch, override afterExecute to inspect both paths, or use
CompletableFuture with whenComplete. For scheduled tasks it is worse, see the next question.
Quiz yourself on Executors and thread pools Suggest a correction