Class Lifecycle.Resources<E extends Exception>

java.lang.Object
io.jenetics.internal.util.Lifecycle.Resources<E>
All Implemented Interfaces:
Lifecycle.ExtendedCloseable<E>, AutoCloseable
Direct Known Subclasses:
Lifecycle.IOResources
Enclosing class:
Lifecycle

public static sealed class Lifecycle.Resources<E extends Exception> extends Object implements Lifecycle.ExtendedCloseable<E> permits Lifecycle.IOResources
This class allows collecting one or more AutoCloseable objects into one. The registered closeable objects are closed in reverse order.

Using the Resources class can simplify the creation of dependent input streams, where it might be otherwise necessary to create nested try-with-resources blocks.

try (var resources = new Resources<IOException>()) {
    final var fin = resources.add(new FileInputStream(file), Closeable::close);
    if (fin.read() != -1) {
        return;
    }
    final var oin = resources.add(new ObjectInputStream(fin), Closeable::close);
    // ...
}
  • Constructor Details

    • Resources

      public Resources(Collection<? extends Lifecycle.ThrowingRunnable<? extends E>> releases)
      Create a new Resources object, initialized with the given resource release methods.
      Parameters:
      releases - the release methods
    • Resources

      @SafeVarargs public Resources(Lifecycle.ThrowingRunnable<? extends E>... releases)
      Create a new Resources object, initialized with the given resource release methods.
      Parameters:
      releases - the release methods
    • Resources

      public Resources()
      Create a new, empty Resources object.
  • Method Details

    • add

      public <C> C add(C resource, Lifecycle.ThrowingConsumer<? super C,? extends E> release)
      Registers the given resource to the list of managed resources.
      Type Parameters:
      C - the resource type
      Parameters:
      resource - the new resource to register
      release - the method, which releases the acquired resource
      Returns:
      the registered resource
      Throws:
      NullPointerException - if one of the given arguments is null
    • add

      public <C extends Lifecycle.ExtendedCloseable<? extends E>> C add(C resource)
      Registers the given resource to the list of managed resources.
      Type Parameters:
      C - the resource type
      Parameters:
      resource - the new resource to register
      Returns:
      the registered resource
      Throws:
      NullPointerException - if one of the given arguments is null
    • close

      public void close() throws E
      Specified by:
      close in interface AutoCloseable
      Specified by:
      close in interface Lifecycle.ExtendedCloseable<E extends Exception>
      Throws:
      E