- Non-daemon threads are also known as ‘user’ threads.
- JVM will not exit even if only 1 non-daemon (i.e. user) thread is alive. On the other hand, JVM will exit even if multiple daemon threads are alive.
- When JVM halts, daemon threads are abruptly abandoned; due to that finally blocks are not executed. Because of this reason, daemon threads should be used sparingly and it is not advisable to use for tasks that perform I/O operations. Assume if you are using daemon threads to establish connection with Database and in the finally clause you are closing the DB connections. If JVM halts, then finally clause will not be executed. It means DB connections will not be gracefully closed. This can lead to connection leaks on the Database side.
- Most of the JVM threads are daemon threads. Few of them are listed below:
- Garbage Collection Threads
- Finalizer Thread
- RMI threads
- Compiler Thread
- When a new thread is created, it inherits the daemon status of its parent. You can make a thread daemon thread or non-daemon thread by invoking setDaemon(boolean). But this method should be invoked before thread is started.
- When a Java Virtual Machine starts up, there is a single non-daemon thread which invokes main() method of the designated class. That’s why all the child threads created by the main thread are non-daemon by default because main thread is non-daemon.
- To know how many threads are daemon and non-daemon threads in your application, capture thread dump from your application and upload it to fastthread.io. It will parse and let you know what percentage of your threads are daemon and non-daemon.
July 16, 2017 at 12:16 pm
when the jvm crashed or killed the non daemon thread also is not guaranteed to execute the finally block. at this point it is no different with non daemon thread.