Daemon thread in Java | Code Factory
2 min readApr 29, 2020
Reference Link : Link
Donate : Link
Daemon thread is a low priority thread that runs in background to perform tasks such as garbage collection.
- They can not prevent the JVM from exiting when all the user threads finish their execution.
- JVM terminates itself when all user threads finish their execution
- If JVM finds running daemon thread, it terminates the thread and after that shutdown itself. JVM does not care whether Daemon thread is running or not.
- It is an utmost low priority thread.
Methods :
1. void setDaemon(boolean status)
This method is used to mark the current thread as daemon thread or user thread. For example if I have a user thread tU then tU.setDaemon(true) would make it Daemon thread. On the other hand if I have a Daemon thread tD then by calling tD.setDaemon(false) would make it user thread.
Syntax :
public final void setDaemon(boolean on)Marks this thread as either a daemon thread or a user thread. The Java Virtual Machine exits when the only threads running are all daemon threads.This method must be invoked before the thread is started.Parameters:
on - if true, marks this thread as a daemon thread
Throws:
IllegalThreadStateException - if this thread is alive
2. boolean isDaemon():
This method is used to check that current is daemon. It returns true if the thread is Daemon else it returns false.
Syntax :
public final boolean isDaemon()Tests if this thread is a daemon thread.Returns:
true if this thread is a daemon thread; false otherwise.
DaemonTest.java
package com.codeFactory;/**
* @author code.factory
*
*/
public class DaemonTest {public static void main(String[] args) {
new WorkerThread().start();try {
Thread.sleep(7500);
} catch (InterruptedException e) {
// handle here exception
}System.out.println("Main Thread ending") ;
}}class WorkerThread extends Thread {public WorkerThread() {
// When false, (i.e. when it's a user thread),
// the Worker thread continues to run.
// When true, (i.e. when it's a daemon thread),
// the Worker thread terminates when the main
// thread terminates.
setDaemon(true);
}public void run() {
int count = 0;while (true) {
System.out.println("Hello from Worker "+count++);try {
sleep(5000);
} catch (InterruptedException e) {
// handle exception here
}
}
}
}
Output :
Hello from Worker 0
Hello from Worker 1
Main Thread endingpackage com.codeFactory;/**
* @author code.factory
*
*/
public class DaemonTest extends Thread {public DaemonTest(String name) {
super(name);
}
public void run() {
if(Thread.currentThread().isDaemon()) {
System.out.println(getName() + " is Daemon Thread");
} else {
System.out.println(getName() + " is User Thread");
}
}
public static void main(String[] args) {
DaemonTest d1 = new DaemonTest("d1");
DaemonTest d2 = new DaemonTest("d2");
d1.setDaemon(true);
d1.start();
d2.start();
}}
Output :
d1 is Daemon Thread
d2 is User Thread