[英]use try-with-resources to close a Closeable
我有一个Map<Key, Closeable>
,如果从地图上删除了一个钥匙,我想关闭Closeable
。 通常我有类似的东西:
Closeable c = map.remove(key);
c.close();
我的Eclipse警告我“资源'c'应该由try-with-resource管理”,因此编写以下内容更好吗?
try (Closeable c = map.remove(key)) {}
在我的特殊实现中,我有一个Closeable
的子类,其中close()
不会引发IOException
,因此不需要任何异常处理。
我只是忽略此警告,如果您要自己管理关闭操作,则只需调用close()
。 空的资源尝试看起来很奇怪。
考虑扩展Map,因此关闭操作将在删除时自动执行:
public class CloseableMap<K,V extends Closeable> extends HashMap<K,V> {
@Override
public R remove(K key) {
V resource = super.remove(key);
if (resource != null) {
resource.close();
}
return resource;
}
}
try-with-resources的要点是:
Closeable
资源的打开是在try
语句中完成的 try
语句的块内 close()
会自动为您调用。 所以你建议的代码:
try(Closeable c = map.remove(key)) {}
...不满足try-with-resource的要求,因为您没有在块内使用资源。 大概您的Closeable
在此语句之前已经打开。
我猜您有一些代码可以打开一堆资源,完成工作,然后通过遍历地图将它们全部关闭。
没关系,有时是不可避免的。 但是在可能的情况下,使用相同的方法将open()
和close()
合并在一起,并在finally
块中包含close()
,这样比较干净,这样一眼便可以看到每个open()
都有一个对应的close()
并且可以确定总是调用close()
。
MyCloseable c = MyCloseable.open(...);
try{
// do stuff with c;
} finally {
try {
c.close();
} catch (IOException e) {
// ...
}
}
一旦做到这一点,尝试资源就可以使事情变得更加整洁:
try(MyCloseable c = MyCloseable.open(...)) {
// do stuff with c;
}
如果您的需求意味着您无法打开和关闭相同的方法,则只需坚持使用显式的close()
并忽略警告。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.