Class Recycler<T,​E extends Exception>

  • Type Parameters:
    T - The type to recycle.
    E - An exception that can be thrown while acquiring an instance of the type to recycle, or use an unchecked exception type such as RuntimeException if none.
    All Implemented Interfaces:
    AutoCloseable
    Direct Known Subclasses:
    RecyclerExceptionless

    public abstract class Recycler<T,​E extends Exception>
    extends Object
    implements AutoCloseable
    Recycler for instances of type T, where instantiating this type may throw checked exception E.
    • Constructor Detail

      • Recycler

        public Recycler()
    • Method Detail

      • newInstance

        public abstract T newInstance()
                               throws E extends Exception
        Create a new instance. This should either return a non-null instance of type T, or throw an exception of type E.
        Returns:
        The new instance.
        Throws:
        E - If an exception of type E was thrown during instantiation.
        E extends Exception
      • acquire

        public T acquire()
                  throws E extends Exception
        Acquire on object instance of type T, either by reusing a previously recycled instance if possible, or if there are no currently-unused instances, by allocating a new instance.
        Returns:
        Either a new or a recycled object instance.
        Throws:
        E - if newInstance() threw an exception of type E.
        IllegalArgumentException - if newInstance() returned null.
        E extends Exception
      • acquireRecycleOnClose

        public RecycleOnClose<T,​E> acquireRecycleOnClose()
                                                        throws E extends Exception
        Acquire a Recyclable wrapper around an object instance, which can be used to recycle object instances at the end of a try-with-resources block.
        Returns:
        Either a new or a recycled object instance.
        Throws:
        E - If anything goes wrong when trying to allocate a new object instance.
        E extends Exception
      • close

        public void close()
        Free all unused instances. Calls AutoCloseable.close() on any unused instances that implement AutoCloseable.

        The Recycler may continue to be used to acquire new instances after calling this close method, and then this close method may be called again in future, i.e. the effect of calling this method is to simply clear out the recycler of unused instances, closing any AutoCloseable instances.

        Specified by:
        close in interface AutoCloseable
      • forceClose

        public void forceClose()
        Force-close this Recycler, by forcibly moving any instances that have been acquired but not yet recycled into the unused instances list, then calling close() to close any AutoCloseable instances and discard all instances.