Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

Java daemon thread

farenda 2015-10-06 0

Problem:

How to create Java daemon thread? How to create it? What are its properties? In the following example we’ll show Java daemon threads in action.

Solution:

In the below code we’ll create and start 5 daemon threads. Each of them will sleep for 3 seconds to mark that they are really running. The main thread will finish just after creating all the threads:

package com.farenda.java.lang;

import java.util.concurrent.TimeUnit;

public class ThreadDaemon {

    private static class SampleThread extends Thread {
        private final int id;

        public SampleThread(int id) {
            this.id = id;
        }

        @Override
        public void run() {
            System.out.println("Running thread " + id);
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                System.out.println("Interrupted!");
            } finally {
                System.out.println("Finally in thread " + id);
            }
            System.out.println("Stopping thread " + id);
        }
    }

    public static void main(String[] args) {
        System.out.println("Starting threads:");
        for (int i = 1; i <= 5; ++i) {
            Thread t = new SampleThread(i);
            // Daemon trigger:
            t.setDaemon(true);
            t.start();
        }
        System.out.println("Stopping program");
    }
}

Note that we use TimeUnit class to call sleep() method instead of Thread.sleep(). Since Java 5 this is the preferred way, because its simple more readable.

When we run the above program we can see that the program ends without giving the daemon threads a chance to end properly and execute their finally blocks:

Starting threads:
Running thread 1
Running thread 2
Running thread 3
Running thread 4
Stopping program

Here’s the same program, but with one, small change – commented out setDaemon(true) line:

Starting threads:
Running thread 1
Running thread 2
Running thread 3
Running thread 4
Stopping program
Running thread 5
Finally in thread 1
Stopping thread 1
Finally in thread 2
Stopping thread 2
Finally in thread 3
Stopping thread 3
Finally in thread 4
Stopping thread 4
Finally in thread 5
Stopping thread 5

As you can see, when the threads are not daemons, the program is waiting for them to finish and calls finally block.

Another important thing is that threads created from daemon threads are also daemon threads!

Share with the World!
Categories Java Tags java, java-concurrency
Previous: Java Thread priority
Next: Java ExecutorService example

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2021

sponsored