Class AutoCloser

java.lang.Object
com.complexible.common.base.AutoCloser
All Implemented Interfaces:
AutoCloseable

public final class AutoCloser extends Object implements AutoCloseable
This class is an equivalent of Guava's Closer, that supports AutoCloseables. See https://github.com/google/guava/issues/1020 Also, this class contains static utility methods for closing multiple AutoCloseables at once.
  • Method Details

    • close

      public static <E extends Exception> void close(Iterable<? extends AutoCloseable> theCloseables) throws E
      Throws:
      E
    • close

      public static void close(AutoCloseable... theCloseables)
    • close

      public static <T extends Throwable> void close(Consumer<T> errConsumer, Iterable<? extends AutoCloseable> theCloseables)
    • close

      public static <T extends Throwable> void close(Consumer<T> errConsumer, AutoCloseable... theCloseables)
    • closeSuppressedBy

      public static void closeSuppressedBy(Exception theE, AutoCloseable... theCloseables)
    • create

      public static AutoCloser create()
      Creates a new AutoCloser.
    • register

      public <C extends AutoCloseable> C register(@Nullable C closeable)
      Registers the given closeable to be closed when this AutoCloser is closed.
      Returns:
      the given closeable
    • rethrow

      public RuntimeException rethrow(Throwable e) throws Exception
      Stores the given throwable and rethrows it. Note: Be sure to declare all of the checked exception types your try block can throw when calling an overload of this method so as to avoid losing the original exception type.

      This method always throws, and as such should be called as throw closer.rethrow(e); to ensure the compiler knows that it will throw.

      Returns:
      this method does not return; it always throws
      Throws:
      Exception - when the given throwable is an Exception
    • close

      public void close()
      Closes all AutoCloseable instances that have been added to this AutoCloser. If an exception was thrown in the try block and passed to one of the exceptionThrown methods, any exceptions thrown when attempting to close a closeable will be suppressed. Otherwise, the first exception to be thrown from an attempt to close a closeable will be thrown and any additional exceptions that are thrown after that will be suppressed.
      Specified by:
      close in interface AutoCloseable
    • applyAndCloseOnError

      public static <O, I extends AutoCloseable, E extends Exception> O applyAndCloseOnError(I theClosable, Function<I,O> theAction, Function<Throwable,E> theErrMapper) throws E
      Executes the action on the closeable and closes it immediately upon failure. Leaves the closeable unclosed otherwise because it can be used while the result is processed (e.g. if the result is a query result set).
      Throws:
      E