chr0mzie
chr0mzie

Reputation: 191

Ensure infinitely looping threads are stopped when main application crashes

I have created a Runnable class responsible for monitoring a directory for file changes.

... imports ...

public class ExamplePathWatch implments Runnable {
    ...
    private boolean isRunning = true;
    ...

    @Override
    public void run() {
        while(isRunning) {
            [1]... wait for a file change ...
            [2]... notify listeners of file change (if any) ...
        }
    }

    public synchronized void stopPathWatch() {
        isRunning = false;
        ... interrupt [1] and allow the thred to exit immediately...
    }

The thread pauses at [1] until a file change occurs, or stopPathWatch() method is called which sets isRunning = false and interrupts current waiting at [1].

Right before the main application exits, the stopPathWatch() is called which allows the thread to exit and the entire application to completely terminate.

My problem is that when there is an application crash, the main application terminates, without the stopPathWatch() being called. Therefore the application keeps running indefinitely in the background until it is killed through the OS.

As there is quite active development on the application and not all exceptions are handled, is there a recommended way to ensure the child thread is stopped no matter how the main application terminates?

Thanks

Upvotes: 2

Views: 593

Answers (2)

Filipe Fedalto
Filipe Fedalto

Reputation: 2540

You can add it as a shutdown hook:

Runtime.getRuntime().addShutdownHook(new Thread() {
    public void run() {
        stopPathWatch();
    }
});

This code would have to go somewhere in your program.

Upvotes: 1

Ian Roberts
Ian Roberts

Reputation: 122384

You could run the ExamplePathWatch as a daemon thread. Only threads that are not marked as daemon will prevent the application from exiting.

Upvotes: 8

Related Questions