Home » Core Java » threads » Application exits when all daemon threads exit

About Byron Kiourtzoglou

Byron Kiourtzoglou
Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.

Application exits when all daemon threads exit

In this example we shall show you how to create a daemon thread in order to force an application to exit. We have created a class, MyDaemonThread that extends the Thread and overrides its run() method. In short:

  • In its run() method the thread tests if it is a daemon thread, with isDaemon() API method of Thread and sleeps for one second.
  • We create a new instance of MydaemonThread in a main() method. We mark it as a daemon, using setDaemon(boolean on) API method of Thread, and then the thread’s execution beggins, using its start() API method. The Java Virtual Machine will exit when the only threads running are all daemon threads. Since the only thread running is MydaemonThread, the application exits,

as described in the code snippet below.

package com.javacodegeeks.snippets.core;

import java.util.logging.Level;
import java.util.logging.Logger;

public class DeamonThreadExit {

    public static void main(String[] argv) throws Exception {


  Thread t = new MyDaemonThread();

  t.setDaemon(true);

  t.start();

    }
}

class MyDaemonThread extends Thread {

    MyDaemonThread() {
   
    }

    @Override
    public void run() {


  boolean isDaemon = isDaemon();

  System.out.println("isDaemon:" + isDaemon);

  try {


Thread.sleep(1000);

  } catch (InterruptedException ex) {

  }
    }
}

 
This was an example of how to create a daemon thread in order to force an application to exit in Java.

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of