Close

Java - Daemon Threads

[Last Updated: Feb 7, 2017]

Difference between Daemon and Non Daemon(User Threads) is that: JVM waits for non-daemon threads to finish executing before terminate the main program. On the other hand, JVM doesn't wait for daemon thread to finish. JVM can exist even if daemon threads are still running.

An example for a daemon thread is the garbage collection thread.

By default a new thread is a daemon thread, if the thread which is creating it, is also daemon. The 'main' thread (which invokes the Java main method) is a non-daemon thread, hence all threads created from it are also non-daemon by default. We can make a thread daemon or non-daemon by using method Thread#setDaemon(true/false)

Calling System.exit(0); will terminate the JVM regardless of, running threads are daemon or not.



Daemon Thread Example

The following example creates a daemon background thread to report memory used:

public class MemoryWatcherThread implements Runnable {
    public static void start () {
        Thread thread = new Thread(new MemoryWatcherThread());
        thread.setPriority(Thread.MAX_PRIORITY);
        thread.setDaemon(true);
        thread.start();
    }

    @Override
    public void run () {

        long memoryUsed = getMemoryUsed();
        System.out.println("Memory used :" + memoryUsed + " MB");

        while (true) {
            long memoryUsed1 = getMemoryUsed();
            if (memoryUsed != memoryUsed1) {
                memoryUsed = memoryUsed1;
                System.out.println("Memory used :" + memoryUsed + " MB");
            }
        }
    }

    private long getMemoryUsed () {
        return (Runtime.getRuntime()
                       .totalMemory() - Runtime.getRuntime()
                                               .freeMemory()) / 1024 / 1024;
    }
}

Here's a test Java class which starts the MemoryWatcherThread and then creates a lot of String objects:

import java.util.ArrayList;
import java.util.List;

public class MainApp {
    static List<String> list = new ArrayList<>();
    public static void main (String[] args) throws InterruptedException {

        MemoryWatcherThread.start();
        for (int i = 0; i < 100000; i++) {
            String str = new String("str"+i);
            list.add(str);
        }
      System.out.println("end of main method");
    }
}

Output:

Memory used :6 MB
Memory used :7 MB
Memory used :8 MB
Memory used :10 MB
Memory used :11 MB
Memory used :12 MB
Memory used :14 MB
Memory used :15 MB
Memory used :16 MB
Memory used :17 MB
Memory used :19 MB
Memory used :20 MB
Memory used :21 MB
end of main method
Memory used :23 MB

Process finished with exit code -1

In above output, the time when main method finishes, the JVM also terminates even though MemoryWatcherThread is still running, it should run infinitely because of while(true) loop. Comment out the line thread.setDaemon(true); and you will see that JVM never terminates.

Using System.exit() at the end of main method, will terminate JVM even for non-daemon thread.

Example Project

Dependencies and Technologies Used:

  • JDK 1.8
  • Maven 3.0.4

Java Daemon Thread Example Select All Download
  • java-daemon-thread
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • MemoryWatcherThread.java

    See Also