Class Recycler<T extends Closeable,E extends Exception>

  • Type Parameters:
    T - The type to recycle.
    E - An exception type that can be thrown while acquiring an instance of the type to recycle.
    All Implemented Interfaces:
    AutoCloseable

    public abstract class Recycler<T extends Closeable,E extends Exception>
    extends Object
    implements AutoCloseable
    Recycle instances of type T. The method T#close() is called when this class' own close() method is called. Use RuntimeException for type E if the newInstance() method does not throw an exception. Example usage: // Autoclose the Recycler when last instance has been released try (Recycler<ZipFile, IOException> recycler = new Recycler<>() { @Override public ZipFile newInstance() throws IOException { return new ZipFile(zipFilePath); } }) { // Repeat the following as many times as needed, on as many threads as needed try { ZipFile zipFile = recycler.acquire(); try { // Read from zipFile -- don't put recycler.acquire() in this try block, otherwise the // finally block will try to release the zipfile even when recycler.acquire() failed // [...] } finally { recycler.release(zipFile); zipFile = null; } } catch (IOException e) { // May be thrown by recycler.acquire() } }
    • Constructor Detail

      • Recycler

        public Recycler()
    • Method Detail

      • newInstance

        public abstract T newInstance()
                               throws E extends Exception
        Create a new instance.
        Returns:
        The new instance.
        Throws:
        E - If an exception of type E was thrown during instantiation.
        E extends Exception
      • acquire

        public Recycler.Recyclable acquire()
                                    throws E extends Exception
        Acquire a Recyclable wrapper around an object instance. Use in try-with-resources.
        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()
        Calls close() on all the unused instances. May be called multiple times, if acquire() is called again after close().
        Specified by:
        close in interface AutoCloseable