What is the Thread.setdaemon() method in Java?

The Thread.setdaemon() method is used to set a thread either as a daemon thread or as a user-defined thread. It signals JVMJava Virtual Machine to stop the daemon thread or the program execution when all the threads are daemon.

Note: Daemon threads are low priority threads that execute in the background to perform low priority tasks like a user-defined thread service, garbage collection, and so on.

Syntax

final void setDaemon(boolean on)

Parameter values

The Thread.setdaemon() method takes a single boolean type argument.

  • on: If this value is set to true, then the current thread is marked as a daemon thread.

Return value

A voidno value method does not return anything.

Exceptions

The following exceptions can occur from the setdaemon() method:

  • IllegalThreadStateException: If a thread was started and has not been completed yet, then the setdaemon() method will throw this exception.
  • SecurityException: If the current thread does not have access to modify the thread, then the setdaemon() method will throw this exception.

Note: We can also learn to check whether a thread is a daemon thread or not from this shot.

Code example

// Program to test setDaemon() method
// Main class
public class Main extends Thread {
// run method for threads
public void run() {
//check either daemon thread or not
if(Thread.currentThread().isDaemon()) {
System.out.println("Daemon thread");
}
else {
System.out.println("User defined thread");
}
}
public static void main(String[] args) {
// create four threads
Main thread1= new Main();
Main thread2= new Main();
Main thread3= new Main();
Main thread4= new Main();
// set thread1 to daemon thread
thread1.setDaemon(true);
// invoke run() method
thread1.start();
// set thread2 to daemon thread
thread2.setDaemon(true);
// start remaining threads
thread2.start();
thread3.start();
thread4.start();
}
}

Code explanation

  • Line 7: We invoke the isDaemon() method to check if the thread is a daemon thread.
  • Lines 16–19: We create four threads by instantiating the Main.class and extending the Thread class.
  • Lines 21 and 25: We set the thread1 and thread2 user threads as daemon threads by calling the setDaemon(true) method.
  • Lines 27–29: We invoke the start() method to start the threads that we created earlier. Then, we call the run() (see line 5) method to check whether this thread is a daemon thread.

Free Resources