Reputation: 2558
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.
Upvotes: 0
Views: 729
Reputation: 15028
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.
You best bet is to have SomeWriter
also implement AutoCloseable
and use the writer itself in the try-with-resources block, as in
try (SomeWriter writer = new SomeWriter()) {
}
// here, the Metrics will also have been closed.
Upvotes: 2