Open ryanhaining opened 5 years ago
This might help with internal bug 80534298, which is the bug that's supposed to be referenced in: https://github.com/google/guava/blob/89138e916d8c1445fafb40adb7c858a9a8e920ab/guava/src/com/google/common/collect/Streams.java#L142
That assumes that this would live in a package usable from common.collect
, though (i.e., "not common.io
").
I wanted to agree here, but seeing as the defacto usage of AutoClosable is try with resources; it stands to reason the implementors here want to explicitly call out the need to register resources with a closer.
The existing
Closer
utility is great forCloseable
but notAutoCloseable
. I have encountered the need for a utility that can safely close a dynamic number of resources in try with resources. Python hascontextlib.ExitStack
to handle this exact issue with context managers, its use speaks to its usefulness. I'm using the nameClosingStack
as a placeholder here, which would of course implementAutoCloseable
The usefulness can be demonstrated in two ways. First, when the number of resources is not known until runtime (a List of filenames where all files must be opened at the same time).
Second, less necessarily, when the number of resources is known at compile-time, but it is unwieldy to nest try-with-resources blocks
ClosingStack#close
would close registered objects in reverse order of registration. LikeCloser
,ClosingStack#close
would create an exception object and suppress every exception thrown by its registered objects, and only throw if it encountered an exception when closing its registered resources.Sample implementation on stackoverflow.
Given than many
AutoCloseable
types don't actually throw, I see the utility around a companion class with a non-throwingclose
I'd be happy to implement this myself, modelling it after the existing
Closer
's code and tests.