Daemon thread in java with example

Daemon threads are low priority background threads which provide services to user threads. It’s life depends on user threads. If no user thread is running then JVM can exit even if daemon threads are running. JVM do not wait for daemon threads to finish.
Daemon threads perform background tasks such as garbage collection, finalizer  etc.
The only purpose of daemon thread is to serve user thread so if there are no user threads, there is no point of JVM to run these threads, that’s why JVM exits once there are no user threads.

Two method related to daemon thread

Public void setDaemon(boolean status) :
This method can be used to mark thread as user  or daemon thread. If you put setDaemon(true), it makes thread as daemon.
 
Public boolean isDaemon()
This method can be used to check if thread is daemon or not.

Daemon Thread example:

When you run above program, you will get below output:

Thread 1 is user thread
Thread 3 is user thread
Thread 2 is daemon thread

Please note that you can not convert user thread to daemon thread once it is started otherwise it will throw IllegalThreadStateException.

When you run above program, you will get below output:

Thread 1 is user threadException in thread “main”
Thread 2 is user thread
Thread 3 is user thread
java.lang.IllegalThreadStateException
at java.lang.Thread.setDaemon(Thread.java:1388)
at org.arpit.java2blog.DaemonThreadMain.main(DaemonThreadMain.java:28)

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *