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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 3: Understanding Janus
  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 2: Understanding Neo4j
  • How to Introduce a New API Quickly Using Micronaut
  • Introducing Graph Concepts in Java With Eclipse JNoSQL

Trending

  • Prioritizing Cloud Security Risks: A Developer's Guide to Tackling Security Debt
  • Introduction to Retrieval Augmented Generation (RAG)
  • ITBench, Part 1: Next-Gen Benchmarking for IT Automation Evaluation
  • Driving DevOps With Smart, Scalable Testing
  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
18.8K 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

  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 3: Understanding Janus
  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 2: Understanding Neo4j
  • How to Introduce a New API Quickly Using Micronaut
  • Introducing Graph Concepts in Java With Eclipse JNoSQL

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!