我有一个WatchService
抛出了下面的代码ClosedWatchServiceException
:如何在应用程序关闭时终止WatchService?
final WatchService watchService = FileSystems.getDefault().newWatchService();
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
try {
watchService.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
WatchKey key = null;
while (true) {
key = watchService.take(); //throws ClosedWatchServiceException
//execution
}
我怎样才能安全地关闭该服务没有得到例外呢?或者我应该忽略关闭,因为任何线程在终止应用程序时都会被终止?