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.
KeepThreadAliveExample:
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() { @Override public void run() { try { System.out.println(Thread.currentThread().getName() + " waiting..."); keepAliveLatch.await(); } catch (InterruptedException e) { } } }, "KeepThreadAliveThread"); keepAliveThread.setDaemon(false); // keep this thread alive (non daemon thread) until we shutdown Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { System.out.println("Thread shutdownhook called"); keepAliveLatch.countDown(); } }); } public static void main(String[] args) throws InterruptedException { KeepThreadAliveExample threadAlive = new KeepThreadAliveExample(); threadAlive.keepAliveThread.start(); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Calling exit..."); System.exit(1); } }
Output:
false 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: javaNonDaemonThread.zip