DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Getting Started With Agentic Workflows in Java and Quarkus
  • Building AI-Powered Java Applications With Jakarta EE and LangChain4j
  • Alternative Structured Concurrency
  • Jakarta EE 12: Entering the Data Age of Enterprise Java

Trending

  • Build Self-Managing Data Pipelines With an LLM Agent
  • The Hidden Bottlenecks That Break Microservices in Production
  • Visualizing Matrix Multiplication as a Linear Combination
  • AWS Managed Database Observability: Monitoring DynamoDB, ElastiCache, and Redshift Beyond CloudWatch
  1. DZone
  2. Coding
  3. Java
  4. Creating Daemon Thread in Java

Creating Daemon Thread in Java

By 
Vinish Kapoor user avatar
Vinish Kapoor
·
May. 22, 20 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
19.3K Views

Join the DZone community and get the full member experience.

Join For Free

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
xxxxxxxxxx
1
 
1
setDaemon(boolean isDaemon)


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
xxxxxxxxxx
1
34
 
1
// JavaDaemonTest.java
2
3
public class JavaDaemonTest {
4
5
    public static void main(String args[]) {
6
        // Create runnable action for daemon
7
        Runnable daemonRunner = new Runnable() {
8
            public void run() {
9
                // Repeat forever
10
                while (true) {
11
                    System.out.println("I'm a Daemon.");
12
                    // Sleep for half a second
13
                    try {
14
                        Thread.sleep(500);
15
16
                    } catch (InterruptedException ignored) {
17
18
                    }
19
                }
20
            }
21
        };
22
        // Create and start daemon thread
23
        Thread daemonThread = new Thread(daemonRunner);
24
        daemonThread.setDaemon(true);
25
        daemonThread.start();
26
        // Sleep for five seconds
27
        try {
28
            Thread.sleep(5000);
29
30
        } catch (InterruptedException ignored) {
31
        }
32
        System.out.println("Done.");
33
    }
34
}


Test

Shell
xxxxxxxxxx
1
 
1
java JavaDaemonTest


Output

Plain Text
xxxxxxxxxx
1
11
 
1
I'm a Daemon.
2
I'm a Daemon.
3
I'm a Daemon.
4
I'm a Daemon.
5
I'm a Daemon.
6
I'm a Daemon.
7
I'm a Daemon.
8
I'm a Daemon.
9
I'm a Daemon.
10
I'm a Daemon.
11
Done.


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.

Java (programming language)

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

Opinions expressed by DZone contributors are their own.

Related

  • Getting Started With Agentic Workflows in Java and Quarkus
  • Building AI-Powered Java Applications With Jakarta EE and LangChain4j
  • Alternative Structured Concurrency
  • Jakarta EE 12: Entering the Data Age of Enterprise Java

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook