Daemon and Non-Daemon threads in Java

Lakshini Kuganandamurthy
2 min readApr 4, 2022

--

This was a very confusing topic for me!!! After some digging, I was able to understand the concept and would like to share it with you all!!!

Let’s go step by step!!! First, let’s see what each term means and then debate how JVM deals with it!!!

What are Non-Daemon threads???

Non-daemon threads are user threads designed to do specific, complex tasks. These are high priority threads that run in the foreground. They are often referred to as “normal threads” that we see and use in day to day coding. Also, any thread created from the Main thread is a non-daemon/user thread. Non daemon / user threads are created usually by the Java application.

What are Daemon Threads???

These are low priority threads that run in the background, which provide services to user threads running in the same Java application. Daemon threads are mostly created by JVM to perform background tasks and they run automatically e.g. garbage collection(gc), finalizer etc…

If a programmer wants to create a daemon thread, they can do so by using the setDaemon(true) method. This method sets the “daemon” status of the thread to “true” making the thread daemon. This method can only be called after creating the thread and before starting (using start() method) that specific thread. If the setDaemon() method is called while the thread is running, it will throw an IllegalThreadStateException. Observe the code snippet below.

Task class — a Thread Group
Main class

Another important point to note is that any new thread spawned or created from a daemon thread also becomes a daemon thread because threads inherit the daemon status from the parent threads.

Differences between Daemon and Non-Daemon threads

Ok, let’s understand how JVM deals with these threads!!!

When you run your Java application using ‘java <Name of .class file without the .class extension>” e.g. java HelloWorld, the “java” in the command tells the operating system to create a JVM instance. JVM when started, creates a non-daemon thread which is also known as the “Main” thread. This thread looks for the main() method (public static void main(String args[])) and invokes it. The main() method is the entry point to your Java application.

Any threads created in the main method is said to be the child threads of the main thread. Therefore, any newly created threads inherit the “daemon” status of their parent thread. That is the reason all the threads created in the main() method, are non daemon by default, because main thread is non daemon.

Have more content!!! 😅

--

--

Lakshini Kuganandamurthy

A passionate individual eager to learn and improve. Associate Software Engineer, Virtusa.