Releasing resources of Java 7 WatchService

怎甘沉沦 提交于 2019-12-05 08:28:11

I think that all you need to do is close() the service. I know you said that you think that you do this already, but I suspect that you are missing some. For instance, you could be failing to close service instances in the case of an exception. You should treat a WatchService instance as other IO resources and close it in a finally block; e.g.

WatchService ws = ...
try {
    // use it ...
} finally {
    ws.close();
}

or using the Java 7 "try with resource" syntax.

try (WatchService ws = ...) {
    // use it ...
}

When the WatchService is closed, it should immediately free any O/S level resources that it holds.


The only other possibility is that you have run into some Java bug in the WatchService implementation.

If I am reading the Javadoc right, you need only one WatchService, which you instantiate at start and close() at end of app.

You submit via .register the paths and events you want to register one at a time, and get back a WatchKey. You keep these WatchKeys around, perhaps in a ConcurrentMap keyed by Path.

When you want to remove one, simply call cancel() on the WatchKey and remove from Map.

WatchService

Path.Register

WatchKey

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!