YouTip LogoYouTip

Java Cleaner Class

`java.lang.ref.Cleaner` is a tool introduced in Java 9 for managing object cleanup, providing a safe way to clean up resources during garbage collection. It can replace the `finalize` method by performing cleanup operations when objects are no longer in use to release external resources, and is more efficient and reliable than `finalize`.\n\n### 1. The Role of `Cleaner`\n\n`Cleaner` allows us to register a cleanup action that will automatically execute when an object becomes unreachable (i.e., is about to be garbage collected). Typical application scenarios include:\n\n* Automatically release non-Java memory resources, such as closing files, database connections, socket connections, etc.\n* Replace `finalize` to achieve automatic resource release, avoiding resource leaks caused by forgetting to call the `close()` method.\n\n### 2. Basic Usage of `Cleaner`\n\nHere is the basic usage of `Cleaner`:\n\n* Create a `Cleaner` instance: `Cleaner.create()`.\n* Create an object that needs cleanup and register it with a cleanup action in the `Cleaner`. When the object is no longer referenced, the cleanup action will automatically execute.\n\n### 3. Usage Example\n\nThe following example demonstrates how to use `Cleaner` to create a resource that needs cleanup, and automatically perform cleanup operations when the object becomes unreachable:\n\n## Example\n\n```java\nimport java.lang.ref.Cleaner;\n\npublic class CleanerExample {\n\n// Create a Cleaner instance\n\nprivate static final Cleaner cleaner = Cleaner.create();\n\n// Define a resource that requires cleanup\n\nstatic class Resource implements AutoCloseable {\n\n// Cleanup task - used to release resources\n\nprivate final Cleaner.Cleanable cleanable;\n\nResource(){\n\n// Register a cleanup task to execute a cleanup action when the Resource instance becomes unreachable\n\nthis.cleanable= cleaner.register(this, new ResourceCleaner());\n\nSystem.out.println("Resource initialized");\n\n}\n\n// Clean up resources\n\nprivate static class ResourceCleaner implements Runnable{\n\n @Override\n\npublic void run(){\n\nSystem.out.println("Cleaning up resource...");\n\n}\n\n}\n\n@Override\n\npublic void close(){\n\n// Proactively release resources and cancel the cleanup task registered with the Cleaner\n\n cleanable.clean();\n\nSystem.out.println("Resource closed");\n\n}\n\n}\n\npublic static void main(String[] args){\n\n// Use the resource\n\ntry(Resource resource =new Resource()){\n\nSystem.out.println("Using resource...");\n\n}// Automatically call close() to manually clean up resources\n\n// If close() is not called, the GC will execute the cleanup task\n\nnew Resource();// Do not call close(), wait for the GC to trigger cleanup\n\nSystem.gc();// Hint the GC to run (cannot guarantee immediate execution of cleanup)\n\n}\n\n}\n\n### 4. Code Explanation\n\n* **Cleaner Instance**: `Cleaner.create()` creates a `Cleaner` instance used to register resources that need cleanup.\n* **Register Cleanup Task**: In the `Resource` class, calling `cleaner.register(this, new ResourceCleaner())` registers the current object with the `Cleaner`, specifying the cleanup task `ResourceCleaner`.\n* **Automatic Cleanup**: When the `Resource` instance has no other strong references and is about to be garbage collected, `Cleaner` will automatically call `ResourceCleaner.run()`, outputting "Cleaning up resource...".\n* **Manual Cleanup**: Through the `close()` method, actively call `cleanable.clean()` to immediately clean up the resource and cancel the `Cleaner` task.\n\n### 5. Characteristics and Advantages of `Cleaner`\n\n* **Efficient**: `Cleaner` is managed by the JVM, avoiding the inefficient performance issues of `finalize`.\n* **Avoids `finalize` Delays**: Tasks registered with `Cleaner` can be executed promptly after objects become unreachable, rather than waiting for the garbage collector to delay the call.\n* **Controllability**: `Cleaner` allows actively calling `clean()` to clean up resources, and automatically cancels the task after cleanup to avoid repeated cleanup.\n* **Memory and Resource Safety**: Reduces the risk of manually managing resources, ensuring proper release of system resources.\n\n### 6. Use Cases for `Cleaner`\n\n`Cleaner` is suitable for managing resources that need automatic release, especially when `try-with-resources` cannot be used. Here are typical application scenarios:\n\n* **Native Resources**: Used to manage non-heap memory resources, such as `DirectByteBuffer`, JNI, or other native resources.\n* **Cache Cleanup**: Automatically clean up related cache data when objects are garbage collected.\n* **Non-blocking Resource Cleanup**: Used for non-blocking resource cleanup tasks, such as notifying other services that an object has been garbage collected.\n\n### 7. Precautions\n\n* **Use in Moderation**: `Cleaner` is mainly used for special scenarios, such as ensuring leak-free non-Java resources. For simple resource management, `try-with-resources` is more suitable.\n* **Uncontrollable Execution Time**: Although `Cleaner` cleanup tasks are more timely than `finalize`, the exact execution time of cleanup tasks still depends on the garbage collection time, making it unsuitable for resource management with strict timing requirements.\n* **Caution with Resource-intensive Cleanup Tasks**: Avoid executing overly complex or long-running operations in `Cleaner`, as this may affect garbage collection performance.\n\nOverall, `java.lang.ref.Cleaner` is the recommended resource cleanup tool in Java, providing an efficient and reliable way to manage resources.
← Tailwindcss TutorialNodejs Build App β†’