2015-05-06 76 views
1

我有一个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 
} 

我怎样才能安全地关闭该服务没有得到例外呢?或者我应该忽略关闭,因为任何线程在终止应用程序时都会被终止?

回答

3

首先说明你的代码没有什么错。您只需在关机期间适当地处理ClosedWatchServiceException。这是因为在执行jvm关机期间,执行watchService.take()的线程在该操作中被阻塞。因此,一旦手表服务关闭,屏蔽的线程将被解除阻塞。

您可以通过在致电watchService.close()之前中断正在运行watchService.take()的线程来阻止此操作。这应该给你一个InterruptedException,你可以处理。但take的合同并没有说明在抛出异常时要考虑的事件的顺序。所以你仍然可以结束ClosedWatchServiceException

所以你可以有一个易失性标志来指示应用程序关闭。在获得ClosedWatchServiceException后,您可以评估该标志,然后优雅地退出(如果该标志已设置)。

相关问题