🎉 Special Offer !    Code: GET300OFF    Flat ₹300 OFF on every Java Course
Grab Deal 🚀

Daemon Thread in Java  


Introduction
  • A Daemon Thread in Java is a special type of thread that runs in the background and provides support services to user threads.
  • If all user threads are finished, the JVM will automatically stop/kill all daemon threads and shut down.
  • Use of Daemon Threads:
    • Perform background tasks without blocking program termination.
    • Provide supporting services like memory cleanup and resource management.
    • Help in running periodic monitoring or housekeeping tasks in applications.
  • Real-World Examples where Daemon Threads are used:
    • Garbage Collection: JVM’s garbage collector is a daemon thread that automatically frees memory.
    • Background Logging: Threads writing logs asynchronously in applications.
    • Monitoring Services: Threads checking for system health, performance or connections in servers.
    • Auto-Save Functionality: In editors/IDEs where changes are saved in the background without disturbing the user’s work.
  • For Daemon Threads, Java has provided two important methods:
    1. public final void setDaemon(boolean on)
      • Used to mark a thread as daemon thread. Must be called before start().
    2. public final boolean isDaemon()
      • Returns true if the thread is a daemon thread, otherwise false.
  • Program (Spell Checker Daemon Thread):
    class SpellCheckerDaemon extends Thread
    {
        @Override
        public void run()
        {
            if (isDaemon())
            {
                System.out.println("Spell Checker Daemon is running in the background...");
            }
    
            // Simulating background spell-check task
            while (true)
            {
                System.out.println("Checking spelling in background...");
                try
                {
                    Thread.sleep(1000); // Pause for demonstration
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }
    }
    
    public class MainApp
    {
        public static void main(String[] args) throws Exception
        {
            SpellCheckerDaemon spellChecker = new SpellCheckerDaemon();
    
            // Mark as daemon before starting
            spellChecker.setDaemon(true);
    
            spellChecker.start();
    
            System.out.println("Main thread: User is typing in the editor...");
            Thread.sleep(3000); // Simulate user typing
    
            System.out.println("Main thread work finished. JVM will exit now.");
        }
    }
  • Key Points about Daemon Threads:
    • They are low-priority background threads.
    • JVM terminates daemon threads automatically when all user threads finish.
    • They are created by calling setDaemon(true) on a thread before starting it.