Daemon Thread Java Example


What is Java Daemon Thread Example?

Daemon threads are service-oriented threads. A service-oriented thread, as the name indicates, serves all other threads. They die after every thread in the process dies, or to say, just before the process exits (no way related with the run() method execution). They are created before any thread is created and dies after every thread dies. For example, the JVM comes with a service thread, garbage collector which removes the garbage (unwanted objects etc.) generated while the process is going on.

The daemon threads are given lowest priority as they should come into action when no other thread is active as process execution (that gives output) must be of highest priority. A normal thread can be converted into a daemon thread with the following simple statement.

t1.setDaemon(true);

The boolean value true indicates t1 should be converted into a daemon thread. If false or if the statement is completely omitted, the thread is a non-daemon thread.

t1.isDaemon();

To test a thread is daemon or not, isDaemon() method is useful. It returns true if the thread is daemon, else false.

Salient points with Daemon Threads

  1. When the parent is daemon, the child thread also gets the status of deamon.
  2. Daemon threads should not be used with regular operations like I/O and transaction management (which are not atomic) etc.
  3. Daemon threads are executed at the background with supporting tasks (like handling requests) needed for the execution of normal threads and can be assigned the responsibility of managing resources.
  4. A process exits after all threads finish their job and only daemon threads remain.
  5. Daemon threads always given the least priority of 1.
  6. Daemon thread will be exeucted when no other thread is running.
  7. Properties to a thread like setting daemon and priority etc. should be done before start is called. Once a thread is running, we cannot change their properties. Sometimes, JVM throws IllegalThreadStateException.
  8. Threads by default are not daemon.
  9. When only daemon threads exist, JVM simply exits without executing finally blocks and unwind stacks etc.

Pass your comments to improve the quality of this tutorial "Daemon Thread Java Example".

Leave a Comment

Your email address will not be published.