Daemon vs non-daemon threads

JVM (Java Virtual Machine) is the layer between Java application and operating system and its sole purpose is to execute any program that is compiled to Java bytecode.

Whenever you run a Java application, an instance of JVM is created and when the application completes, the instance dies.

How does JVM know that application is completed?

To answer this question, there is another concept to explain.

In JVM, there are two kinds of threads that run.

  1. Daemon Threads: You can think of them as the threads that maintains the environment and program, threads that are used by JVM for itself. Like the thread that does garbage collection for example. But these kinds of threads can also be created in the application by the programmer.
  2. Non-daemon Threads: These are user threads. For example, initial thread that starts running at the execution of main() function is a non-daemon thread.

The main difference between these two is that JVM continues to execute until there is at least one non-daemon thread running. (or exit() is invoked. In that case, it doesn’t matter if there are non-daemon threads running or not.)

However JVM doesn’t wait other daemon threads to finish before exiting. So you have to be careful if you’re using daemon threads in your application, because once all non-daemon threads are done, JVM will just exit. finally blocks will not be executed, stacks will not be emptied. Those threads will be just abandoned.

You might be asking right now that “why would I use a daemon thread in my application, anyway?”. The answer is that if the thread you’re creating is for the program, it’s probably a daemon thread. For example, you might want to send a log to a monitory tool about the usage of your program as long as it runs, so you create a daemon thread and it keeps running as long as the program doesn’t exit. You don’t want that kind of thread to prevent program from exiting.

So here is an example about these threads:

public class SoYouThinkYouCanThread extends Thread {
public static void main(String[] args) {
System.out.println("Hello!");
SoYouThinkYouCanThread sytyct = new SoYouThinkYouCanThread();

// This is by default is set to false. It inherits this from the running
// parent thread.
sytyct.setDaemon(false);

sytyct.start();
System.out.println("Good bye!");
}
public void run() {
System.out.println("Warming up!");
boolean shouldIKeepRunning = true; while (shouldIKeepRunning) {
try {
Thread.sleep(1000);
} catch (InterruptedException exc) {
System.out.println("Oops!");
}
System.out.println("Running!");
}
}
}

if(sytyct.isDaemon())

output =

Hello!
Good bye!
Warming up!

The daemon thread will die before getting a chance to run! Because, all non-daemon threads(e.g. main function) finished running, so JVM doesn’t really care about daemon threads, it simply exits.

if(!sytyct.isDaemon())

output =

Hello!
Good bye!
Warming up!
Running!
Running!
Running!
Running!
...

Since we made it a non-daemon thread and told that it should keep running (forever!), it never stops executing. It just keeps running!

--

--

--

a geek who loves to understand the reasons behind things... and colors... Colors are cool.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Top Technical Articles I read in 2018

Murderers of Optimization

🐼 Learn to code with Pandas 🐼

DevSecOps: Automating people and tools to create a secure environment

Getting Started as a Web Developer in 2018

Gin HTTP Framework for Golang / Go: Setting up a JSON Web Token (JWT) Authorization Middleware

Flutter: Google’s Most Ambitious Framework

Virtual Events — First Take Aways

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mehmet Akcay

Mehmet Akcay

a geek who loves to understand the reasons behind things... and colors... Colors are cool.

More from Medium

InjectIntoKeyValue in Eclipse Collections

How long should I wait to retry a failed async job? Here is the Exponential backoff

Why you should not use “currentTimeMillis” when you calculate elapsed time?

SOLID Principles (Journey for writing readable and maintainable code)