Java Reference
In-Depth Information
Listing 7.23 illustrates a way to structure a worker thread within a thread pool. If a task
throws an unchecked exception, it allows the thread to die, but not before notifying the frame-
work that the thread has died. The framework may then replace the worker thread with a new
thread, or may choose not to because the thread pool is being shut down or there are already
enough worker threads to meet current demand. ThreadPoolExecutor and Swing use
this technique to ensure that a poorly behaved task doesn't prevent subsequent tasks from
executing. If you are writing a worker thread class that executes submitted tasks, or calling
untrusted external code (such as dynamically loaded plugins), use one of these approaches to
prevent a poorly written task or plugin from taking down the thread that happens to call it.
Listing 7.23. Typical Thread-pool Worker Thread Structure.
7.3.1. Uncaught Exception Handlers
The previous section offered a proactive approach to the problem of unchecked exceptions.
The Thread API also provides the UncaughtExceptionHandler facility, which lets
you detect when a thread dies due to an uncaught exception. The two approaches are comple-
mentary: taken together, they provide defense-indepth against thread leakage.
When a thread exits due to an uncaught exception, the JVM reports this event to an
application-provided UncaughtExceptionHandler (see Listing 7.24 ) ; if no handler
exists, the default behavior is to print the stack trace to System.err . [8]
Search WWH ::




Custom Search