Do you know Java: Daemon Thread
Application terminates when all threads are terminated. But what if some of them run endlessly?
Sometimes threads run until a condition is met, sometimes they run endlessly.
Once a thread is created and then started, it runs parallel with the main execution.
Our app terminates when all threads are terminated including our main
method as well.
What if a thread is infinite and still running though the main is already terminated?
Let us see an example of that we have in our thread and how main
looks like.
public class Daemon extends Thread {
@Override
public void run() {
int count = 0;
while (true) {
System.out.println(count++);
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread t = new Daemon();
t.start();
System.out.println("t started");
Thread.sleep(3500);
System.out.println("ended");
}
The output is as follows.
t started
0
...
6
ended
7
8
...
As we see, thread still runs after the main
terminated. To change the behaviour of our app, let us set the thread to daemon.
Thread t = new Daemon();
t.setDaemon(true);
t.start();
// ...
And the output is:
t started
0
...
6
ended
What we should know about daemon threads:
- Thread is non-daemon by default
- Thread can be set as daemon before start
- JVM terminates when all remaining threads are terminated
- Daemon thread terminates when all non-daemon threads are terminated including
main
- Once
main
terminates and a thread instance runs infinitely, daemon thread results infinite execution.
Documentation about Daemon
Code can be found: https://github.com/torokmark/do-you-know-java