Java Cleaner Class
java.lang.ref.Cleaneris a tool introduced in Java 9, used to manage object cleanup, providing a safe way to clean up resources during garbage collection. It can replacefinalizethe method, which releases external resources by executing cleanup operations when the object is no longer used, and isfinalizemore efficient and reliable.
1. CleanerRole
CleanerAllows us to register a clean-up action, which will be automatically executed when the object becomes unreachable (i.e., about to be garbage collected). Typical application scenarios include:
- Automatically release non-Java memory resources, such as closing files, database connections, socket connections, etc.
- Replace
finalize, implement automatic resource release, avoid resource leaks caused by forgetting to callclose()the method.
2. CleanerBasic Usage
The following isCleanerthe basic usage:
- Create
Cleaneran instance:Cleaner.create()。 - Create an object that needs cleanup, and register it along with the cleanup action to
Cleanerthe Cleaner. When the object is no longer referenced, the cleanup action will be executed automatically.
3. Usage Example
The following example demonstrates how to useCleanerto create a resource that needs cleanup, and automatically perform cleanup operations when the object becomes unreachable:
Example
public class CleanerExample {
// Create a Cleaner instance
private static final Cleaner cleaner = Cleaner.create();
// Define a resource that needs cleanup
static class Resource implements AutoCloseable {
// Cleanup task - used to release resources
private final Cleaner.Cleanable cleanable;
Resource() {
// Register the cleanup task; execute the cleanup action when the Resource instance becomes unreachable
this.cleanable = cleaner.register(this, new ResourceCleaner());
System.out.println("Resource initialized");
}
// Clean up resources
private static class ResourceCleaner implements Runnable {
@Override
public void run() {
System.out.println("Cleaning up resource...");
}
}
@Override
public void close() {
// Actively release resources and cancel the cleanup task registered with Cleaner
cleanable.clean();
System.out.println("Resource closed");
}
}
public static void main(String[] args) {
// Use resources
try (Resource resource = new Resource()) {
System.out.println("Using resource...");
} // Automatically call close() to manually clean up resources
// If close() is not called, GC will execute the cleanup task
new Resource(); // Do not call close(), wait for GC to trigger cleanup
System.gc(); // Hint GC to run (cleanup is not guaranteed to execute immediately)
}
}
4. Code Explanation
- Cleaner instance::
Cleaner.create()creates anCleanerinstance, used to register resources that need cleanup. - Register cleanup task:In
Resourcethe class, callcleaner.register(this, new ResourceCleaner())to register the current object toCleanerthe Cleaner, specifying the cleanup taskResourceCleaner。 - Automatic cleanup:When the
Resourceinstance has no other strong references and is about to be garbage collected,CleanerCleaner will automatically callResourceCleaner.run()close(), outputting "Cleaning up resource...". - Manual cleanup:By
close()actively calling the methodcleanable.clean(), immediately clean up resources and cancelCleanerthe Cleaner task.
5. Characteristics and Advantages of Cleaner
- Efficient:
CleanerManaged by the JVM, it avoidsfinalizethe inefficient performance problems. - Avoid finalize delay:
CleanerRegistered tasks can be executed promptly after the object becomes unreachable, rather than waiting for delayed invocation by the garbage collector. - Controllability:
CleanerAllows actively callingclean()to clean up resources, and automatically cancels the task after cleanup, avoiding duplicate cleanup. - Memory and resource safety: Reduces the risk of manual resource management and ensures correct release of system resources.
6. Usage Scenarios of Cleaner
CleanerSuitable for managing resources that need automatic release, especially wheretry-with-resourcesuse is not possible. The following are typical application scenarios:
- Native resources: Used to manage non-heap memory resources, such as
DirectByteBuffer, JNI, or other local resources. - Cache cleanup: When the object is garbage collected, automatically clean up related cached data.
- Non-blocking resource cleanup: Used for non-blocking resource cleanup tasks, such as notifying other services that the object has been collected.
7. Notes
- Use with moderation:
CleanerIt is mainly used for special scenarios, such as ensuring leak-free non-Java resources. For simple resource management,try-with-resourcesis more suitable. - Uncontrollable execution time: Although
Cleanerits cleanup task is morefinalizetimely, but the exact execution time of the cleanup task still depends on the garbage collection time, making it unsuitable for resource management with strict timeliness requirements. - Use caution with resource-intensive cleanup tasks: Avoid
Cleanerexecuting overly complex or long-running operations in it, so as not to affect garbage collection performance.
Overall,java.lang.ref.Cleanerit is the recommended resource cleanup tool in Java, providing an efficient and reliable way of resource management.