Search code examples
javaautocloseable

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.


Solution

  • 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.