I am creating a variable amount of AutoCloseable
objects in a try-with-resources
block. At any point of exit, I want all of the allocated resources closed.
I can imagine writing something myself to do this, but is there an existing utility similar to Python's contextlib.ExitStack that will close allocated resources? I would expect it to look like this:
try (ExitStack exitStack = new ExitStack()) {
List<Widget> widgets = new ArrayList<>();
for (...) {
widgets.add(exitStack.add(new Widget()));
}
// use widgets
}
(Note: this is not this question because I don't know how many resources I'll have ahead of time.
Hey close voters I'm not asking for a library, I'm asking how you would accomplish the task of safely closing a dynamic number of AutoCloseable
s, if there's a language feature for it, great, if there's a standard library function, also great, if I have to write my own, fine. If you'd like to recommend a third-party library in common use that has this in it then sure.
try-with-resources
inside the for-loop? – ManifestoExitStack
shouldn't be that hard since it probably would just contain a collection ofAutoCloseables
and just close them in its ownclose()
method (using a simple loop and catching exceptions per element). – Pinupclose()
on each element. It might not look as pretty, but it will let you handle everything together. – WilhelminaAutoCloseable
that is a collection ofAutoCloseable
) – Reece