Keeping main thread running with Thread.sleep vs CountDownLatch

Sujeet :

I want my main thread to be running, as I have some listener that will be listening to request/messages in another thread and I don't want my main thread to die.

Which one is better

CountDownLatch

public static void main(String[] args) throws InterruptedException {

    startListener();
    CountDownLatch latch = new CountDownLatch(1);
    latch.await();

}

Or While with sleep

public static void main(String[] args) throws InterruptedException {

    startListener();
    while (true){
        Thread.sleep(1000);
    }

}
Karol Dowbecki :

Assuming your listener thread is a non-daemon thread you can let the main thread finish. The JVM will continue to run as long as there are non-daemon threads executing.

CountDownLatch would be a better solution if you plan to implement a graceful shutdown. You can hit the latch and let the main thread finish by executing a cleanup logic. Think how the application will shut down e.g. you get a SIGTERM singal when listener is reading a message from the queue, what then?

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=76159&siteId=1