{{announcement.body}}
{{announcement.title}}

Creating Daemon Thread in Java

DZone 's Guide to

Creating Daemon Thread in Java

The Java runtime environment takes advantage of a special type of thread for background tasks. It’s called a daemon thread.

· Java Zone ·
Free Resource

In this tutorial, you will learn how to create Daemon Thread in Java.

What is Daemon Thread in Java?

The Java runtime environment takes advantage of a special type of thread for background tasks. It’s called a daemon thread, where the daemon is pronounced “demon.” These support threads manage behind-the-screen tasks like garbage collection.

Daemon threads are special because if the only threads running in the VM are daemon threads, the Java runtime will shut down or exit.

Note

When working with daemon threads in Java, be espaicially careful to remember that the daemon thread’s task may be stopped in the middle of execution when the runtime shuts down.

Creating a thread as a daemon in Java is as simple as calling the setDaemon() method. A setting of true means the thread is a daemon; false means it is not. By default, all threads are created with an initial value of false.

Java


Create Daemon Thread in Java Example

In the following example, we will create a daemon thread in Java that demonstrates the behavior of daemon threads. The main thread creates a daemon thread that displays a message every half second. The main thread then sleeps for five seconds. While the daemon thread is still executing, the program ends because the only currently executing threads are daemon threads.

Java


Test

Shell


Output

Plain Text


It is possible that on extra “I’m Daemon.” message will appear after “Done.” if the timing is right (or wrong, depending upon your point of view). Were the new thread not marked as a daemon, the program would continue indefinitely until you manually stopped it. Most likely by pressing Ctrl+C.

Note

If you want a daemon java.util.Timer, pass in true to the calss constructor. Then, any scheduled tasks will be daemons.

Topics:
daemon thread ,java ,reactive programming ,tutorial

Published at DZone with permission of Vinish Kapoor . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}