Class SilentDispose


  • public final class SilentDispose
    extends Object
    Utility class for disposing of resources without propagating any exception that Resource.close() might throw.
    • Method Detail

      • dispose

        public static void dispose​(Object obj,
                                   InternalLogger logger)
        Attempt to dispose of whatever the given object is.

        This method works similarly to Resource.dispose(Object), except any exception thrown will be logged instead of propagated.

        If the object is AutoCloseable, such as anything that implements Resource, then it will be closed. If the object is ReferenceCounted, then it will be released once.

        Any exceptions caused by this will be logged using the given logger. The exception will be logged at log-level WARN.

        Parameters:
        obj - The object to dispose of.
        logger - The logger to use for recording any exceptions thrown by the disposal.
      • trySilentDispose

        public static void trySilentDispose​(Object obj,
                                            InternalLogger logger)
        Attempt to dispose of whatever the given object is, but only if it is disposable.

        This method works similarly to dispose(Object, InternalLogger), except the object is only disposed of if it is accessible.

        Any exceptions caused by the disposal of the object will be logged using the given logger. The exception will be logged at log-level WARN.

        Parameters:
        obj - The object to dispose of.
        logger - The logger to use for recording any exceptions thrown by the disposal.
      • autoClosing

        public static AutoCloseable autoClosing​(Object obj)
        Return an AutoCloseable for the given object, which can be used to dispose of it using a try-with-resources clause.

        The benefit of this approach is that exceptions are correctly handled if both the try-body, and the resource disposal, throws.

        This is not a silent operation, in that exceptions from resource disposal will propagate. However, the try-with-resources clause will guarantee that resource disposal exceptions won't shadow any exceptions from the try-body

        Parameters:
        obj - The object to dispose of.
        Returns:
        An AutoCloseable that will dispose of the given object when closed.