javajava-8try-with-resourcesautocloseable

Array or collection of "Autocloseable" in Java8


Autocloseable should always be used with try-with-resources. At least Intellij inspection suggests it. So, if I have a code that produces Foo that implements Autocloseable I should do:

try (final Foo foo = getFoo()) {
    foo.doSomething();
}

But what if I have function that returns Foo[]? Or function that accepts Foo[] (or Collection<Foo>) as its argument?

How can I use it with try-with-resources? Looks at the following functions:

Foo[] getFoos();
doAll(Foo... foo);

I want to do something line doAll(getFoos())

How can I do that?


Solution

  • Try-with-resources statement can only close those resources, that were declared and assigned within its header. So the only way is to make the Collection you are getting implement AutoCloseable or wrap it into your AutoCloseable extension, so its close() method will be called by T-W-R. Like:

    try (SomeAutoCloseableCollction col = getAutoCloseables()) {
            System.out.println("work");
    }  //col.close() gets called
    

    For an array, I'm afraid there is no way, since you can't extend it and make it implement some interface.


    If you were to close collection by yourself, may be look at Apache Drill project and class org.apache.drill.common.AutoCloseables - it does exactly that, closing lots of AutoCloseables by itself.