Skip to content

Instantly share code, notes, and snippets.

@stanio
Created June 19, 2023 08:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stanio/0fb64b5e580d8bd5fd734609cc543561 to your computer and use it in GitHub Desktop.
Save stanio/0fb64b5e580d8bd5fd734609cc543561 to your computer and use it in GitHub Desktop.
Fail-safe Resource Initialization
/*
* This module, both source code and documentation,
* is in the Public Domain, and comes with NO WARRANTY.
*/
//package ;
import java.util.ArrayList;
import java.util.List;
/**
* Temporary collection for initializing multiple {@code AutoCloseable}
* resources. If initialization of a resource fails, all previously opened
* resources get automatically closed as with {@code try-with-resources} block:
* <pre>
* private FileInputStream in;
* private FileOutputStream out;
*
* Constructor() throws IOException {
* VolatileResources resources = VolatileResource.open();
* this.in = resources.add(() -> new FileInputStream("..."));
* this.out = resources.add(() -> new FileOuputStream("..."));
* }</pre>
* <p>
* If all resource initialization succeeds, the volatile collection is
* normally discarded. It is then responsibility of the user to close the
* initialized resources.</p>
*/
public class VolatileResources {
private final List<AutoCloseable> resources = new ArrayList<>(3);
public static VolatileResources open() {
return new VolatileResources();
}
public <R extends AutoCloseable, E extends Throwable>
R add(ThrowingSupplier<R, E> resourceInitializer) throws E {
try {
R res = resourceInitializer.get();
resources.add(res);
return res;
} catch (Throwable e) {
closeSafely(e);
throw e;
}
}
private void closeSafely(Throwable root) {
resources.forEach(it -> {
try {
it.close();
} catch (Throwable e) {
root.addSuppressed(e);
}
});
}
@FunctionalInterface
public static interface ThrowingSupplier<R, E extends Throwable> {
R get() throws E;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment