Class Recycler<T extends AutoCloseable,E extends Exception>

  • All Implemented Interfaces:
    AutoCloseable

    public abstract class Recycler<T extends AutoCloseable,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 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

      • acquire

        public T acquire()
                  throws E extends Exception
        Acquire or allocate an instance.
        Throws:
        E extends Exception
      • release

        public void release​(T instance)
        Release/recycle an instance.
      • close

        public void close()
        Call this only after all instances have been released.
        Specified by:
        close in interface AutoCloseable
      • newInstance

        public abstract T newInstance()
                               throws E extends Exception
        Create a new instance.
        Throws:
        E extends Exception