Java Reference
In-Depth Information
status of the thread that created it, so by default any threads created by the main thread are
also normal threads.
Normal threads and daemon threads differ only in what happens when they exit. When a
thread exits, the JVM performs an inventory of running threads, and if the only threads that
are left are daemon threads, it initiates an orderly shutdown. When the JVM halts, any re-
maining daemon threads are abandoned— finally blocks are not executed, stacks are not
unwound—the JVM just exits.
Daemon threads should be used sparingly—few processing activities can be safely aban-
doned at any time with no cleanup. In particular, it is dangerous to use daemon threads for
tasks that might perform any sort of I/O. Daemon threads are best saved for “housekeep-
ing” tasks, such as a background thread that periodically removes expired entries from an
in-memory cache.
Daemon threads are not a good substitute for properly managing the lifecycle of services
within an application.
7.4.3. Finalizers
The garbage collector does a good job of reclaiming memory resources when they are no
longer needed, but some resources, such as file or socket handles, must be explicitly returned
to the operating system when no longer needed. To assist in this, the garbage collector treats
objects that have a nontrivial finalize method specially: after they are reclaimed by the
collector, finalize is called so that persistent resources can be released.
Since finalizers can run in a thread managed by the JVM, any state accessed by a finalizer
will be accessed by more than one thread and therefore must be accessed with synchroniza-
tion. Finalizers offer no guarantees on when or even if they run, and they impose a significant
performance cost on objects with nontrivial finalizers. They are also extremely difficult to
write correctly. [9] In most cases, the combination of finally blocks and explicit close
methods does a better job of resource management than finalizers; the sole exception is when
you need to manage objects that hold resources acquired by native methods. For these reas-
ons and others, work hard to avoid writing or using classes with finalizers (other than the
platform library classes) [EJ Item 6].
Search WWH ::




Custom Search