Class CleanableSupport
java.lang.Object
ecmwf.common.technical.CleanableSupport
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
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic interfaceFunctional interface for user-supplied cleanup logic. -
Constructor Summary
ConstructorsConstructorDescriptionCleanableSupport(Object owner, CleanableSupport.ThrowingRunnable cleanup) Constructs a newCleanableSupportinstance. -
Method Summary
Modifier and TypeMethodDescriptionvoidclose()Explicitly triggers cleanup and releases the resource.booleanChecks whether this resource has already been cleaned.booleanMarks this instance as cleaned.
-
Constructor Details
-
CleanableSupport
Constructs a newCleanableSupportinstance.- Parameters:
owner- the resource owner (typicallythis)cleanup- the cleanup logic to be executed either manually or automatically- Throws:
NullPointerException- if either argument isnull
-
-
Method Details
-
close
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:
trueif this was the first cleanup attempt,falseotherwise
-
isCleaned
public boolean isCleaned()Checks whether this resource has already been cleaned.- Returns:
trueif cleaned,falseotherwise
-