[英]How to implement Autocloseable for resource opened on construction
I am have a resource I open on construction of my object. 我有打开我的对象构造的资源。 I use it to write throughout the lifetime of the object.
我用它来写对象的整个生命周期。 But my application can close without warning and I need to capture this.
但是我的应用程序可以关闭而不会发出警告,我需要捕获这一点。 The class is pretty straightforward.
该类非常简单。
public class SomeWriter {
private Metrics metrics;
public SomeWriter() {
try (metrics = new Metrics()) { // I know I can't but the idea is there
}
}
public void write(String blah) {
metrics.write(blah);
}
public void close() {
metrics.close();
}
So, you get the idea. 这样,您就知道了。 I'd like to "Autoclose" Metrics if the application goes down.
如果应用程序出现故障,我想“自动关闭”指标。
That is not possible with the try-with-resource concept, which is for local scope only. 使用资源试一试的概念是不可能的,仅适用于本地范围。 The way you close the
Metrics
within your close()
is the best you can do. 在
close()
关闭Metrics
的方法是最好的方法。
You best bet is to have SomeWriter
also implement AutoCloseable
and use the writer itself in the try-with-resources block, as in 最好的选择是让
SomeWriter
也实现AutoCloseable
并在try-with-resources块中使用writer本身,例如
try (SomeWriter writer = new SomeWriter()) {
}
// here, the Metrics will also have been closed.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.