Class CleanableSupport

java.lang.Object
ecmwf.common.technical.CleanableSupport

public class CleanableSupport extends Object
CleanableSupport provides robust lifecycle management for resources, supporting both manual and automatic cleanup via Java’s Cleaner.

It allows deterministic cleanup through explicit close() calls, while also registering a fallback cleanup action that will be invoked automatically when the owning object becomes unreachable (garbage collected).

Features:

  • Thread-safe, one-time cleanup (manual or GC-triggered)
  • Logs live and peak instance counts by class, updated periodically
  • Logs resource lifetime and cleanup origin (manual or GC)
  • Breaks reference cycles to ensure GC-triggered cleanup works correctly

Example usage:

public class MyFileResource implements AutoCloseable {

    private final CleanableSupport cleanable;

    public MyFileResource() {
        cleanable = new CleanableSupport(this, () -> {
            // Perform resource cleanup, e.g., closing a file
            if (someConditionFails()) {
                throw new IOException("Failed to close file");
            }
        });
    }

    @Override
    public void close() throws IOException {
        cleanable.close(); // Propagates exception if cleanup fails
    }
}

In the above example, the CleanableSupport ensures the file is closed deterministically via close(), or automatically when the MyFileResource instance is garbage collected.

Since:
2025-06-06
Version:
6.8.7
Author:
Laurent Gougeon
  • Constructor Details

    • CleanableSupport

      public CleanableSupport(Object owner, CleanableSupport.ThrowingRunnable cleanup)
      Constructs a new CleanableSupport instance.
      Parameters:
      owner - the resource owner (typically this)
      cleanup - the cleanup logic to be executed either manually or automatically
      Throws:
      NullPointerException - if either argument is null
  • Method Details

    • close

      public void close() throws IOException
      Explicitly triggers cleanup and releases the resource.

      Once called, the cleanup logic will not be executed again, even if garbage collection later occurs.

      Throws:
      IOException - if the cleanup logic throws an exception
    • markCleaned

      public boolean markCleaned()
      Marks this instance as cleaned.
      Returns:
      true if this was the first cleanup attempt, false otherwise
    • isCleaned

      public boolean isCleaned()
      Checks whether this resource has already been cleaned.
      Returns:
      true if cleaned, false otherwise