Java Daemon Thread Example

When we create a Thread in java, by default it’s a user thread and if it’s running JVM will not terminate the program. When a thread is marked as daemon thread, JVM doesn’t wait it to finish and as soon as all the user threads are finished, it terminates the program as well as all the associated daemon threads.

Thread.setDaemon(true) can be used to create a daemon thread in java. Let’s see a small example of java daemon thread.

package com.journaldev.threads;

public class JavaDaemonThread {

    public static void main(String[] args) throws InterruptedException {
        Thread dt = new Thread(new DaemonThread(), "dt");
        //continue program
        System.out.println("Finishing program");


class DaemonThread implements Runnable{

    public void run() {

    private void processSomething() {
        try {
            System.out.println("Processing daemon thread");
        } catch (InterruptedException e) {

When we execute this program, JVM creates first user thread with main() function and then a daemon thread. When main function is finished, the program terminates and daemon thread is also shut down by JVM.

Here is the output of the above program.

Processing daemon thread
Processing daemon thread
Processing daemon thread
Processing daemon thread
Processing daemon thread
Processing daemon thread
Finishing program

If we don’t set the thread to be run as daemon thread, the program will never terminate even after main thread is finished it’s execution. Try commenting the statement to set thread as daemon thread and run the program.

Usually we create a daemon thread for functionalities that are not critical to system, for example logging thread or monitoring thread to capture the system resource details and their state.


Leave a Reply

Your email address will not be published. For posting CODE wrap them inside <pre class="prettyprint"></pre>. Required fields are marked *