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..
The exceptions you are getting are happening because you aren't controlling your UI events.
A
ClosedWatchServiceExceptionoccurs when you try to use aWatchServicewhoseclose()method has been called. So you are probably callingwatchService.take()or some otherWatchServicemethod after callingclose(). It might happen that thetake()method unblocks after you close theWatchServiceand immediately throws theException.You get a
NullPointerExceptionwithkeybecause you are trying to callcancel()on the instance before having initialized it. I'm guessing it's declared somewhere in your class asBy default, instance reference type variables are initialized to
null. If your execution never takes you throughthen
keywill remainnull.