Daemon vs non-daemon threads

JVM (Java Virtual Machine) is the layer between Java application and operating system and its sole purpose is to execute any program that is compiled to Java bytecode.

Whenever you run a Java application, an instance of JVM is created and when the application completes, the instance dies.

How does JVM know that application is completed?

To answer this question, there is another concept to explain.

In JVM, there are two kinds of threads that run.

  1. Daemon Threads: You can think of them as the threads that maintains the environment and program, threads that are used by JVM for itself. Like the thread that does garbage collection for example. But these kinds of threads can also be created in the application by the programmer.
  2. Non-daemon Threads: These are user threads. For example, initial thread that starts running at the execution of main() function is a non-daemon thread.

The main difference between these two is that JVM continues to execute until there is at least one non-daemon thread running. (or exit() is invoked. In that case, it doesn’t matter if there are non-daemon threads running or not.)

However JVM doesn’t wait other daemon threads to finish before exiting. So you have to be careful if you’re using daemon threads in your application, because once all non-daemon threads are done, JVM will just exit. finally blocks will not be executed, stacks will not be emptied. Those threads will be just abandoned.

You might be asking right now that “why would I use a daemon thread in my application, anyway?”. The answer is that if the thread you’re creating is for the program, it’s probably a daemon thread. For example, you might want to send a log to a monitory tool about the usage of your program as long as it runs, so you create a daemon thread and it keeps running as long as the program doesn’t exit. You don’t want that kind of thread to prevent program from exiting.

So here is an example about these threads:

public class SoYouThinkYouCanThread extends Thread {
public static void main(String[] args) {
System.out.println("Hello!");

if(sytyct.isDaemon())

output =

Hello!
Good bye!
Warming up!

The daemon thread will die before getting a chance to run! Because, all non-daemon threads(e.g. main function) finished running, so JVM doesn’t really care about daemon threads, it simply exits.

if(!sytyct.isDaemon())

output =

Hello!
Good bye!
Warming up!
Running!
Running!
Running!
Running!
...

Since we made it a non-daemon thread and told that it should keep running (forever!), it never stops executing. It just keeps running!

a geek who loves to understand the reasons behind things... and colors... Colors are cool.