threads

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.

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.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button