Java non-daemon thread alive


In this article we will see an example how a thread can be kept alive. JVM exits when the only threads running are all daemon thread so the thread that we are going to start needs to be a non-daemon thread.

In the below example, we start a thread that wait on a latch with count one. Once we decide to shutdown the thread, we release the latch in its shutdown hook.

For the sake of simplicity, we shutdown the thread after waiting for 10 seconds.


package com.javarticles.threads;

import java.util.concurrent.CountDownLatch;

public class KeepThreadAliveExample {
    private final Thread keepAliveThread;
    private final CountDownLatch keepAliveLatch = new CountDownLatch(1);

    public KeepThreadAliveExample() {
        keepAliveThread = new Thread(new Runnable() {
            public void run() {
                try {
                    System.out.println(Thread.currentThread().getName() + " waiting...");
                } catch (InterruptedException e) {
        }, "KeepThreadAliveThread");
        // keep this thread alive (non daemon thread) until we shutdown
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                System.out.println("Thread shutdownhook called");

    public static void main(String[] args) throws InterruptedException {
        KeepThreadAliveExample threadAlive = new KeepThreadAliveExample();
        try {
        } catch (InterruptedException e) {
        System.out.println("Calling exit...");


KeepThreadAliveThread waiting...
Calling exit...
Thread shutdownhook called

Download the source code

This was an example about how to keep a thread alive.

You can download the source code here:

About Author

Ram's expertise lies in test driven development and re-factoring. He is passionate about open source technologies and loves blogging on various java and open-source technologies like spring. You can reach him at [email protected]

Comments are closed.