What is Daemon thread and How to make Daemon thread?

What is Daemon thread and How to make Daemon thread?

What is Daemon thread and How to make Daemon thread?

What is Daemon thread and How to make Daemon thread?
  • The threads which are executing in the background are called Demon threads.
  • Ex… Garbage Collector, Signal Dispatcher, Attach Listener.
  • The main objective of demon threads is to provide support for non-demon threads(main thread)
    • For ex… If the main thread runs with low memory then JVM runs GC to destroy useless objects so that number of byte of free memory will be improved with this free memory main thread can continue its execution.
  • Usually, demon threads having low priority but based on our requirement demon threads can run with high priority also.
  • Daemon threads are useful for background supporting tasks such as garbage collection, releasing memory of unused objects and removing unwanted entries from the cache. Most of the JVM threads are daemon threads.
  • We can check demon nature of a thread by using isDaemon() method of thread class.
    • Public boolean isDaemon();
  • We can change demon nature of a thread by using setDaemon() method.
    • Public void setDemon(boolean b);
    • But changing demon nature is possible before starting of a thread only. After starting a thread if we are trying to change demon nature then we will get RuntimeException saying IllegalThreadStateException.

Leave a Reply

Your email address will not be published. Required fields are marked *

*