Daemon Thread In Java With Example

In this post, we will see Daemon Thread In Java With Example. Let’s see some basics about Daemon thread later we will see some examples.

Daemon Thread In Java With Example

  • Daemon threads are low priority thread which executes in the background.
  • Purpose of Daemon thread – The main purpose of the Daemon thread is to provide support for Non Daemon thread(i.e main thread).
  • Example of Daemon thread – Attach Listener, Reference Handler, Signal Dispatcher, Garbage Collector, Finalizer.
  • The method isDaemon()  is used to check running thread is Daemon or not? Using setDaemon(boolean b), we can make any thread as Daemon.
  • When all Non-Daemon threads finish running, the JVM kills all daemon threads automatically.
  • The method setDaemon must be called before the thread has been started else it will throw an IllegalThreadStateException.

Let’s see an example that will help to understand the use of Daemon thread. Suppose we have created some object which has done their job and because of this JVM is running on low memory. JVM will run Garbage Collector(i.e Daemon thread) which will clean the memory.

Example to check running thread is Daemon or not –

The output is – false

Example to get all running Daemon thread –

The output is –

Daemon Thread name is:- Attach Listener
Daemon Thread name is:- Reference Handler
Daemon Thread name is:- Signal Dispatcher
Daemon Thread name is:- Finalizer

Example to create User define thread and make it Daemon –

The output is –

Thread created using Thread class
Thread-0

The output may vary, I ran the above program multiple times but output was not consistent, after making a user-defined thread as Daemon.

Example where we will call setDaemon() after start() method –

The output is –

Exception in thread “main” Thread-0
java.lang.IllegalThreadStateException
at java.lang.Thread.setDaemon(Unknown Source)
at daemonthread.DaemonThreadExample3.main(DaemonThreadExample3.java:12)

Interview Talk –  Can we define main thread as Daemon thread? Answer is no, we can’t because JVM will start the main thread in beginning and we have already discussed we can’t make any thread as Daemon once it will get started.

Let’s see a quick example –

The output is –

Exception in thread “main” java.lang.IllegalThreadStateException
at java.lang.Thread.setDaemon(Thread.java:1359)
at DaemonThreadExample1.main(DaemonThreadExample1.java:3)

That’s all about Daemon thread in java with example.

You may like.

Thread class docs.

Top