Module xaos.core

Class AutoCloser<T>

  • Type Parameters:
    T - The type of the object wrapped by this class.

    public class AutoCloser<T>
    extends Object
    This utility class allows to use non-AutoCloseable classes in auto-closeable contexts.

    For example, imagine to have the following class:

       public class NotAutoclosable {
         public NotAutoclosable() { ... }
         public void dispose() { ...to be called to free resources... }
         ...
       }

    This class can be used in the following way:

       NotAutoclosable nac = new NotAutoclosable();
    
       try {
         ...use nac.xxx methods...
       } finally {
         nac.dispose();
       }

    AutoCloser simplify things without requiring to modify NotAutoclosable to implement AutoCloseable:

       try { var nacs = AutoCloser.of(new NotAutoclosable()).by(sp -> sp.get().dispose()) ) {
         ...use nacs.get().xxx methods...
       }
    Author:
    Peter Verhas, claudio.rosati@esss.se
    See Also:
    Box old objects to be autoclosable
    • Method Detail

      • of

        public static <T> AutoCloser<T> of​(T resource)
        Returns an instance of this class, wrapping the given resource, to be used in an auto-closable context.
        Type Parameters:
        T - The type of the wrapped resource.
        Parameters:
        resource - The non-AutoCloseable resource to be wrapped.
        Returns:
        An instance of this class to be used an auto-closable context.