Quantcast
Channel: What is a daemon thread in Java? - Stack Overflow
Viewing all articles
Browse latest Browse all 28

Answer by Zahid Khan for What is a daemon thread in Java?

$
0
0

Daemon Thread

Threads that run in the background are called daemon threads.

Example of Daemon Threads:

  1. Garbage Collector.
  2. Signal Dispatcher.

Objective of Daemon Thread:

The main objective of the daemon threads is to provide support to the non-daemon threads.

Additional information about Daemon Thread:

  1. Generally, Daemon threads run in the MIN_PRIORITY however, it is possible to run daemon threads with MAX_PRIORITY as well.

    Example: Usually the GC runs with a MIN_PRIORITY priority, however, once there is a requirement for additional memory. JVM increases the priority of the GC from MIN_PRIORITY to MAX_PRIORITY.



  1. Once the Thread has been started, it can't be changed from Daemon Thread to Non-Daemon Thread that will result in IllegalThreadStateException.

    Example:

    public static void main(String[] args) {    Thread.currentThread().setDaemon(true);}

    Output:

    Exception in thread "main" java.lang.IllegalThreadStateException    at java.base/java.lang.Thread.setDaemon(Thread.java:1403)


  1. If we are branching off a thread, the child thread inherits the nature of the parent thread. If the parent thread is a non-daemon thread automatically the child thread will be non-daemon as well and if the parent thread is a daemon, the child thread will be a daemon as well.

    class Scratch {    public static void main(String[] args) {        CustomThread customThread = new CustomThread();        customThread.start();    }}class CustomThread extends Thread{    @Override    public void run() {        System.out.println(currentThread().isDaemon());    }}

    Output:

     false


  1. When the last non-daemon thread terminates, all the daemon threads get terminated automatically.

    class Scratch {    public static void main(String[] args) {        System.out.println("Main Thread Started.");        CustomThread customThread = new CustomThread();        customThread.setDaemon(true);        customThread.start();        System.out.println("Main Thread Finished.");    }}class CustomThread extends Thread{    @Override    public void run() {        System.out.println("Custom Thread Started.");        try {            sleep(2000);        } catch (InterruptedException ignore) {}        System.out.println("Custom Thread Finished.");  //Won't get executed.    }}

    Output:

    Main Thread Started.Main Thread Finished.Custom Thread Started.

Viewing all articles
Browse latest Browse all 28

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>