Class CloseableRefs<C extends Closeable>

java.lang.Object
io.permazen.util.CloseableRefs<C>
Type Parameters:
C - target object type

@ThreadSafe public class CloseableRefs<C extends Closeable> extends Object
Holds a count of references to a Closeable resource and only close()'s it when the reference count reaches zero.

Instances are thread safe.

  • Field Details

    • target

      protected final C extends Closeable target
  • Constructor Details

    • CloseableRefs

      public CloseableRefs(C target)
      Constructor.

      Initially the reference count is set to one.

      Parameters:
      target - target instance
  • Method Details

    • getTarget

      public C getTarget()
      Get the underlying target instance, which must not yet be closed.

      The returned value should not be closed; that will happen automatically when the reference count goes to zero.

      Returns:
      the underlying Closeable
      Throws:
      IllegalStateException - if reference count is already zeroed
    • ref

      public void ref()
      Increment reference count.
      Throws:
      IllegalStateException - if reference count is already zeroed
    • unref

      public void unref()
      Decrement reference count.
      Throws:
      IllegalStateException - if reference count is already zeroed
    • refs

      public int refs()
      Get current reference count.
      Returns:
      the current number of references to this instance
    • handleCloseException

      protected void handleCloseException(IOException e)
      Handle an exception being thrown by Closeable.close() when closing the target.

      The implementation in CloseableRefs just logs the error.

      Parameters:
      e - exception thrown when closing the target object
    • getLogger

      protected Logger getLogger()
      Get the Logger to use for logging errors.

      The implementation returns the logger associated with this.target.getClass().

    • finalize

      protected void finalize() throws Throwable
      Check that the reference count is zero before finalization.

      If not, that means there was a leak and so the underlying Closeable is closed and an error is logged.

      Overrides:
      finalize in class Object
      Throws:
      Throwable