As per Java documentation, JVM exits only when all the non-daemon threads complete their execution. Even the main method complete execution, all the non-daemon and daemon threads will continue their operations as long as, there is atleast one non-daemon thread running.
What is daemon thread?
Daemon threads are low priority threads, which are mainly used for background processing
How to make a thread Daemon?
Signature
public final void setDaemon(boolean on)
When you set the setDaemon to true for a thread, then it acts as a daemon thread.
How to know whether a thread is daemon or not
isDaemon() method returns true if this thread is a daemon thread; false otherwise.
Let’s experiment the same with below example.
DaemonThreadsDemo.java
package com.sample.app;
import java.util.concurrent.TimeUnit;
public class DaemonThreadsDemo {
static void sleep(int noOfSeconds) {
try {
TimeUnit.SECONDS.sleep(noOfSeconds);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
Runnable runnable1 = new Runnable() {
int counter = 0;
@Override
public void run() {
while (counter < 5) {
counter++;
sleep(1);
System.out.println(Thread.currentThread().getName() + " is running");
}
System.out.println(Thread.currentThread().getName() + " is exiting");
}
};
Runnable runnable2 = new Runnable() {
@Override
public void run() {
while (true) {
sleep(1);
System.out.println(Thread.currentThread().getName() + " is running");
}
}
};
Thread t1 = new Thread(runnable1, "Non-Daemon thread");
Thread t2 = new Thread(runnable2, "Daemon thread");
t2.setDaemon(true);
t1.start();
t2.start();
System.out.println("Main thread finished execution....");
}
}
Output
Main thread finished execution.... Daemon thread is running Non-Daemon thread is running Non-Daemon thread is running Daemon thread is running Non-Daemon thread is running Daemon thread is running Non-Daemon thread is running Daemon thread is running Daemon thread is running Non-Daemon thread is running Non-Daemon thread is exiting
From the output, you can confirm that JVM exits as long as there is no non-daemon thread running.
From java doc, A program terminates all its activity and exits when one of two things happens:
a. All the threads that are not daemon threads terminate.
b. Some thread invokes the exit method of class Runtime or class System, and the exit operation is not forbidden by the security manager.
You may like
Implement a Closeable iterator in Java
Quick guide to generate random data in Java
What are the different cache eviction strategies?
How to call super class method from sub class overriding method?
No comments:
Post a Comment