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();




class MyDaemonThread extends Thread {

    MyDaemonThread() {

    public void run() {

  boolean isDaemon = isDaemon();

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

  try {


  } 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.
Notify of

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

Inline Feedbacks
View all comments
Back to top button