How to stop Java WatchService when is waiting for key?

6.6k views Asked by At

I'm trying to stop my thread where WatchService is working. But how to do that? My WatchService waiting for new update in folder there:

key = watchService.take(); 

I start my Thread there:

private void startButtonActionPerformed(ActionEvent e) {

        stateLabel.setText("monitoring...");

        try {
            watchService = FileSystems.getDefault().newWatchService();
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        watchThread = new WatchThread(watchService, key);
        Thread t = new Thread(watchThread);
        t.start();

    }

My trying to stop:

private void stopButtonActionPerformed(ActionEvent e) {
     try {
        if (watchService!=null) {
            key.cancel();
            watchService.close();
        }
     } catch (IOException e1) {
        e1.printStackTrace();
     }
}

When I try to execute the stop, I get NullPointerException in key. When I'm just closing watchService with watchService.close(), I get another exception: ClosedWatchServiceException.

How to close a WatchService without any exceptions? Sorry for my bad english..

1

There are 1 answers

0
Sotirios Delimanolis On BEST ANSWER

The exceptions you are getting are happening because you aren't controlling your UI events.

A ClosedWatchServiceException occurs when you try to use a WatchService whose close() method has been called. So you are probably calling watchService.take() or some other WatchService method after calling close(). It might happen that the take() method unblocks after you close the WatchService and immediately throws the Exception.

You get a NullPointerException with key because you are trying to call cancel() on the instance before having initialized it. I'm guessing it's declared somewhere in your class as

private WatchKey key;

By default, instance reference type variables are initialized to null. If your execution never takes you through

key = watchService.take(); 

then key will remain null.