Daemon threads in Java are like a service providers for other threads or objects running in the same process as the daemon thread. Daemon threads are used for background supporting tasks and are only needed while normal threads are executing.
If normal threads are not running and remaining threads are daemon threads then the interpreter exits.
When a new thread is created it inherits the daemon status of its parent. Normal thread and daemon threads differ in what happens when they exit. When the JVM halts any remaining daemon threads are abandoned: finally blocks are not executed, stacks are not unwound – JVM just exits. Due to this reason daemon threads should be used sparingly and it is dangerous to use them for tasks that might perform any sort of I/O.
setDaemon(true/false) ?
This method is used to specify that a thread is daemon thread.
public boolean isDaemon() ?
This method is used to determine the thread is daemon thread or not.
Java Example:
package com.crunchify.tutorials; /** * @author Crunchify.com */ public class CrunchifyDaemonThread extends Thread { public static void main(String[] args) { System.out.println("Main Method Entry"); CrunchifyDaemonThread t = new CrunchifyDaemonThread(); t.setDaemon(true); // 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. t.start(); try { Thread.sleep(3000); } catch (InterruptedException x) { } System.out.println("Main Method Exit"); } public void run() { System.out.println("run Method Entry"); try { System.out.println("In run Method: currentThread() is" + Thread.currentThread()); while (true) { try { Thread.sleep(1000); } catch (InterruptedException x) { } System.out.println("In run method.." + Thread.currentThread()); } } finally { System.out.println("run Method Exit"); } } }
Output1: (with t.setDaemon(true)):
Main Method Entry run Method Entry In run Method: currentThread() isThread[Thread-0,5,main] In run method..Thread[Thread-0,5,main] In run method..Thread[Thread-0,5,main] Main Method Exit
When daemon thread is the only threads running in a program – as you see here JVM ends the program
finishing the thread.
Output2: (with t.setDaemon(false)):
Main Method Entry run Method Entry In run Method: currentThread() isThread[Thread-0,5,main] In run method..Thread[Thread-0,5,main] In run method..Thread[Thread-0,5,main] Main Method Exit In run method..Thread[Thread-0,5,main] In run method..Thread[Thread-0,5,main] In run method..Thread[Thread-0,5,main] In run method..Thread[Thread-0,5,main] ... ... ...
As you see here program doesn't exit
when it’s not a daemon thread.
Reference: stackoverflow