Daemon Thread in Java

Daemon thread in java is a service provider thread that provides services to the user thread. Its life depend on the mercy of user threads i.e. when all the user threads dies, JVM terminates this thread automatically. There are many java daemon threads running automatically e.g. gc, finalizer etc. You can see all the detail by typing the jconsole in the command prompt. The jconsole tool provides information about the loaded classes, memory usage, running threads etc.

Daemon thread provides services to user threads for background supporting tasks. It has no role in life than to serve user threads. Daemon thread's life depends on user threads. Daemon thread is a low priority thread. The sole purpose of the daemon thread is that it provides services to user thread for background supporting task. If there is no user thread, why should JVM keep running this thread. That is why JVM terminates the daemon thread if there is no user thread. The java.lang.Thread class provides two methods for java daemon thread.


Table 6.2: Deamon thread
No. Method Description
1 public void setDaemon(boolean status) is used to mark the current
    thread as daemon thread or user thread.
2 public boolean isDaemon() is used to check that current is daemon.


Example File: MyThread.java


\begin{lstlisting}
public class TestDaemonThread1 extends Thread{
public void ...
....start();//starting threads
t2.start();
t3.start();
}
}
\end{lstlisting}

Output


\begin{lstlisting}
daemon thread work
user thread work
user thread work
\end{lstlisting}

If you want to make a user thread as Daemon, it must not be started otherwise it will throw IllegalThreadStateException.

File: MyThread.java


\begin{lstlisting}
class TestDaemonThread2 extends Thread{
public void run(){ ...
...tDaemon(true);//will throw exception here
t2.start();
}
}
\end{lstlisting}
Test it Now
\begin{lstlisting}
Output:exception in thread main: java.lang.IllegalThreadStateException
\end{lstlisting}