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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop
  • ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL
  • Member Spotlight: Shai Almong

Trending

  • AI Coding Agent Guardrails: Finding Gaps in Tool Permissions
  • The Context Window Trap: Why More Context Doesn’t Mean Better AI
  • Nobody Designs an RBAC Mess; Everyone Ends Up With One
  • Beyond @Transactional: Solving the Dual-Write Problem in Distributed Microservices

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Java
  4. Creating Daemon Thread in Java

Creating Daemon Thread in Java

By 
Vinish Kapoor
·
May. 22, 20 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
19.5K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop
  • ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL
  • Member Spotlight: Shai Almong

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • 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