Please enable JavaScript.
Coggle requires JavaScript to display documents.
7.3 Handling Abnormal Thread Termination - Coggle Diagram
7.3 Handling Abnormal Thread Termination
Causes of Premature Thread Death
Main cause: RuntimeException
Not usually caught → propagates up → default behavior: print stack trace + terminate thread.
Any method can throw RuntimeException.
Trusting external code:
Skepticism needed when calling unfamiliar methods.
Especially when calling unknown code through an abstraction like Runnable.
Task-Processing Threads and Risk Mitigation
Threads like:
Worker threads in thread pools.
Swing event dispatch thread.
Constantly call unknown code through abstractions.
Protection mechanisms:
Wrap task calls in try-catch for unchecked exceptions.
Alternatively, use try-finally to inform framework on abnormal exit.
Catching RuntimeException here is justified.
Controversy:
Catching unchecked exceptions might compromise the app.
But allowing app shutdown is worse.
Framework Response to Abnormal Thread Termination
If a task throws an unchecked exception:
Thread dies, but framework is notified before.
Framework options:
Replace the worker thread.
Ignore replacement if shutting down or enough threads exist.
Example: ThreadPoolExecutor, Swing use this approach.
Important when:
Writing a worker thread class executing tasks.
Calling untrusted external code (e.g., plugins).
Uncaught Exception Handlers
Overview
Complementary to proactive exception handling.
Provided by Thread API: UncaughtExceptionHandler.
Detects when a thread dies from an uncaught exception.
JVM behavior:
If no handler → prints stack trace to System.err.
What Should an UncaughtExceptionHandler Do?
Depends on quality-of-service (QoS) requirements.
Common actions:
Log error message and stack trace.
More direct actions:
Restart thread.
Shut down application.
Notify an operator (paging).
Other corrective/diagnostic actions.
Best Practices
In long-running applications:
Always use uncaught exception handlers for threads.
Setting handler for thread pool threads:
Provide a ThreadFactory to ThreadPoolExecutor.
Only the thread owner should set UncaughtExceptionHandler.
Standard thread pools:
Allow pool thread termination on task exception.
Use try-finally to detect and replace thread.
Without failure notification:
Tasks can fail silently, causing confusion.
Special Note: Tasks Submitted via submit vs. execute
Tasks submitted with execute:
Exceptions make it to the uncaught exception handler.
Tasks submitted with submit:
Exceptions are treated as task return status.
If terminated with an exception:
Exception is rethrown by Future.get, wrapped in ExecutionException.