Class CleanableState

java.lang.Object
org.newsclub.net.unix.CleanableState
All Implemented Interfaces:
Closeable, AutoCloseable

@IgnoreJRERequirement public abstract class CleanableState extends Object implements Closeable
This wrapper (along with the Java 8-specific counterpart in src/main/java8) allows us to implement cleanup logic for objects that are garbage-collectable/no longer reachable.

Usage:

  1. Create a subclass of CleanableState and attach it as a private field to the object you want to be cleaned up. You may call that field cleanableState.
  2. Define all resources that need to be cleaned up in this subclass (instead of the observed object itself).
  3. Make sure to not refer the observed object instance itself, as that will create a reference cycle and prevent proper cleanup.
  4. Implement the doClean() method to perform all the necessary cleanup steps.
  5. If the observed class implements close(), it's a good practice to have it just call cleanableState.runCleaner().

Exceptions thrown upon doClean() are either thrown via close() when invoked directly, or, if cleaned during Garbage collection, to the exception handler specified in the constructor or (if none specified) to the default uncaught exception handler.

Implementation details:

Author:
Christian Kohlschütter
  • Field Details

  • Constructor Details

    • CleanableState

      protected CleanableState(Object observed)
      Creates a state object to be used as an implementation detail of the specified observed instance, using the DEFAULT_EXCEPTION_HANDLER.
      Parameters:
      observed - The observed instance (the outer class referencing this CleanableState).
    • CleanableState

      protected CleanableState(Object observed, AFConsumer<Throwable> exceptionHandler)
      Creates a state object to be used as an implementation detail of the specified observed instance, using a custom exception handler.
      Parameters:
      observed - The observed instance (the outer class referencing this CleanableState).
      exceptionHandler - The exception handler.
  • Method Details

    • runCleaner

      public final void runCleaner()
      Explicitly the cleanup code defined in doClean(). This is best be called from a close() method in the observed class.
    • doClean

      protected abstract void doClean() throws IOException
      Performs the actual cleanup. Be sure to always clean up whenever possible, either by tracking potential exceptions or by using try-finally to ensure proper cleanup.
      Throws:
      IOException - on error.
    • inClose

      protected boolean inClose()
      Checks if we're being called from within close().
      Returns:
      true if being called from within close().
    • close

      public final void close() throws IOException
      Specified by:
      close in interface AutoCloseable
      Specified by:
      close in interface Closeable
      Throws:
      IOException