Java Reference
In-Depth Information
When a thread exits by throwing an exception, the default behavior is to print the
name of the thread, the type of the exception, the exception message, and a stack
trace. If this isn't sufficient, you can install a custom handler for uncaught excep‐
tions in a thread. For example:
// This thread just throws an exception
Thread handledThread =
new Thread (() -> { throw new UnsupportedOperationException (); });
// Giving threads a name helps with debugging
handledThread . setName ( "My Broken Thread" );
// Here's a handler for the error.
handledThread . setUncaughtExceptionHandler (( t , e ) -> {
System . err . printf ( "Exception in thread %d '%s':" +
"%s at line %d of %s%n" ,
t . getId (), // Thread id
t . getName (), // Thread name
e . toString (), // Exception name and message
e . getStackTrace ()[ 0 ]. getLineNumber (),
e . getStackTrace ()[ 0 ]. getFileName ()); });
handledThread . start ();
This can be useful in some situations, for example, if one thread is supervising a
group of other worker threads, then this pattern can be used to restart any threads
that die.
Deprecated Methods of Thread
In addition to the useful methods of Thread , there are a number of unsafe methods
that the developer should not use. These methods form part of the original Java
thread API, but were quickly found to be not suitable for developer use. Unfortu‐
nately, due to Java's backward compatibility requirements, it has not been possible to
remove them from the API. The developer simply needs to be aware of them, and to
avoid using them under all circumstances.
y d
Thread.stop() is almost impossible to use correctly without violating concurrent
safety, as stop() kills the thread immediately, without giving it any opportunity to
recover objects to legal states. This is in direct opposition to principles such as con‐
current safety, and so should never be used.
suspend(), resume(), and countStackFrames()
The suspend() mechanism does not release any monitors it holds when it suspends,
so any other thread that attempts to accesses those monitors will deadlock. In
Search WWH ::

Custom Search