Java > Concurrency and Multithreading > Thread Basics > Daemon Threads
Daemon Thread Example: Auto-Saving Application
Demonstrates the use of a daemon thread for automatically saving data in an application. Daemon threads are background threads that provide services to other threads. The JVM exits when only daemon threads are running.
Code Snippet: Daemon Thread for Auto-Saving
This code creates a daemon thread that periodically saves data. The setDaemon(true)
method marks the thread as a daemon. The main thread simulates application work, and after a certain period, the application 'closes'. Because the auto-save thread is a daemon, the JVM exits when the main thread finishes, even if the auto-save thread is still running. If setDaemon(true)
is removed, the application will continue to run infinitely. The auto-save process runs every 5 seconds until the interruption or JVM exit. It is important to add interruption logic to handle the termination properly.
public class AutoSaveDaemon {
public static void main(String[] args) throws InterruptedException {
Thread autoSaveThread = new Thread(() -> {
while (true) {
try {
// Simulate auto-saving data every 5 seconds
Thread.sleep(5000);
System.out.println("Auto-saving data...");
// Add actual saving logic here, e.g., writing to a file
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.out.println("Auto-save interrupted.");
break;
}
}
});
// Set the thread as a daemon thread
autoSaveThread.setDaemon(true);
// Start the auto-save thread
autoSaveThread.start();
// Simulate the main application doing some work
System.out.println("Application is running...");
Thread.sleep(15000); // Run for 15 seconds
System.out.println("Application is closing.");
}
}
Concepts Behind the Snippet
Daemon threads are low-priority threads that run in the background to perform tasks such as garbage collection, auto-saving, or background monitoring. They are designed to support normal threads. The JVM terminates when only daemon threads are left running. Setting a thread as a daemon must be done before it is started using the setDaemon(true)
method. Once started, you cannot change a thread's daemon status.
Real-Life Use Case
Daemon threads are ideal for background tasks like:
Best Practices
setDaemon(true)
before calling start()
.
Interview Tip
Common interview questions related to daemon threads include:
Be prepared to discuss the characteristics, usage scenarios, and potential pitfalls of daemon threads.
When to Use Them
Use daemon threads when:
Memory Footprint
Daemon threads consume memory like any other thread. The memory footprint includes the stack size and any objects allocated by the thread. The memory footprint can be significant if the daemon thread performs memory-intensive operations. It's essential to monitor the memory usage of daemon threads, especially in long-running applications.
Alternatives
Alternatives to daemon threads include:
The choice of alternative depends on the specific requirements of the application and the complexity of the background tasks.
Pros
Cons
FAQ
-
What happens if a daemon thread is interrupted?
When a daemon thread is interrupted, itsinterrupt()
method is called. The thread should handle theInterruptedException
appropriately, typically by cleaning up resources and exiting gracefully. If the thread doesn't handle the interruption, it may continue to run until the JVM exits. -
Can I change a thread's daemon status after it has started?
No, the daemon status of a thread can only be set before it is started. CallingsetDaemon(true)
orsetDaemon(false)
after the thread has been started will throw anIllegalThreadStateException
. -
Are daemon threads always guaranteed to complete their tasks?
No, daemon threads are not guaranteed to complete their tasks. They can be terminated abruptly when the JVM exits. Therefore, it's crucial not to rely on daemon threads for critical operations.