Commit 1d23c9e
committed
feat: Demonstrate daemon threads in Java
WHAT the code does:
- Defines DemonThread extending Thread:
- run() loops infinitely, printing "Hello World!".
- In main():
- Creates DemonThread instance D.
- Marks D as daemon using setDaemon(true).
- Starts D with start(), moving it into runnable state.
- Prints "Main done" and then main thread terminates.
WHY this matters:
- Shows how daemon threads differ from user threads.
- JVM automatically terminates daemon threads when all user threads finish.
- Demonstrates background task behavior (like garbage collector, monitoring, or housekeeping).
- Reinforces lifecycle concepts: even infinite loop threads can be stopped once only daemons remain.
HOW it works:
1. D is created and configured as a daemon thread.
2. D.start() schedules D to run concurrently.
3. main() prints "Main done" and ends.
4. JVM sees only daemon threads remain → shuts down process, killing daemon thread.
5. Output: "Hello World!" may print a few times, but stops once main exits.
Tips and gotchas:
- Must call setDaemon(true) before start(); calling it after throws IllegalThreadStateException.
- Daemon threads are not guaranteed to finish tasks, so avoid them for critical work.
- Best used for background services that support user threads but don’t need to live beyond them.
- Don’t rely on daemon thread output consistency; it may terminate abruptly.
Use-cases / analogies:
- Daemon threads = janitors/housekeepers who clean up as long as the office is open (user threads active).
- Common in loggers, background resource monitoring, or async cache refreshers.
- JVM’s garbage collector itself runs as a daemon.
Short key: java daemon-threads background-task lifecycle jvm-termination.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 4cf8308 commit 1d23c9e
1 file changed
+4
-5
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | 1 | | |
3 | | - | |
4 | | - | |
5 | | - | |
| 2 | + | |
| 3 | + | |
6 | 4 | | |
7 | 5 | | |
8 | 6 | | |
9 | | - | |
10 | 7 | | |
11 | 8 | | |
12 | 9 | | |
13 | 10 | | |
14 | 11 | | |
15 | 12 | | |
16 | 13 | | |
| 14 | + | |
| 15 | + | |
0 commit comments