Java Reference
In-Depth Information
Shutdown hooks can be used for service or application cleanup, such as deleting temporary
files or cleaning up resources that are not automatically cleaned up by the OS. Listing 7.26
shows how LogService in Listing 7.16 could register a shutdown hook from its start
method to ensure the log file is closed on exit.
Because shutdown hooks all run concurrently, closing the log file could cause trouble for
other shutdown hooks who want to use the logger. To avoid this problem, shutdown hooks
should not rely on services that can be shut down by the application or other shutdown hooks.
One way to accomplish this is to use a single shutdown hook for all services, rather than one
for each service, and have it call a series of shutdown actions. This ensures that shutdown
actions execute sequentially in a single thread, thus avoiding the possibility of race condi-
tions or deadlock between shutdown actions. This technique can be used whether or not you
use shutdown hooks; executing shutdown actions sequentially rather than concurrently elim-
inates many potential sources of failure. In applications that maintain explicit dependency
information among services, this technique can also ensure that shutdown actions are per-
formed in the right order.
Listing 7.26. Registering a Shutdown Hook to Stop the Logging Service.
7.4.2. Daemon Threads
Sometimes you want to create a thread that performs some helper function but you don't want
the existence of this thread to prevent the JVM from shutting down. This is what daemon
threads are for.
Threads are divided into two types: normal threads and daemon threads. When the JVM starts
up, all the threads it creates (such as garbage collector and other housekeeping threads) are
daemon threads, except the main thread. When a new thread is created, it inherits the daemon
Search WWH ::




Custom Search