{"id":1605,"date":"2023-07-18T09:51:27","date_gmt":"2023-07-17T21:51:27","guid":{"rendered":"https:\/\/www.ronella.xyz\/?p=1605"},"modified":"2024-04-02T11:05:20","modified_gmt":"2024-04-01T22:05:20","slug":"java-cleaner","status":"publish","type":"post","link":"https:\/\/www.ronella.xyz\/?p=1605","title":{"rendered":"Java Cleaner"},"content":{"rendered":"<p>Java Cleaner is a new feature introduced in Java 9 that allows you to define cleanup actions for groups of objects. <strong>Cleaners are implemented with the Cleanable interface, which descends from Runnable.<\/strong> Each Cleanable represents an object and a cleaning action registered in a Cleaner. Each <strong>Cleanable runs in a dedicated thread<\/strong>. All <strong>exceptions thrown by the cleaning action are ignored<\/strong>.<\/p>\n<blockquote>\n<p>Java 18, marked the finalize method for removal. It is better to avoid the usage of finalize method.<\/p>\n<\/blockquote>\n<p>The most efficient use of Cleaner is to explicitly invoke the clean() method when the object is closed or no longer needed. <strong>Note that the cleaning action must not refer to the object being registered<\/strong>.<\/p>\n<p>Cleaners provide a more reliable way to perform cleanup tasks than relying on finalization. <strong>Finalization is often unreliable because it is not guaranteed to be called before the object is garbage collected.<\/strong> Cleaners, on the other hand, are guaranteed to be called before the object is garbage collected, as long as the clean() method is invoked.<\/p>\n<p>See the sample usage of a Java Cleaner below:<\/p>\n<pre><code class=\"language-java\">import java.lang.ref.Cleaner;\n\npublic class SampleResourceUsage implements AutoCloseable {\n\n    \/**\n     * A cleaner, preferably one shared within a library\n     *\/\n    private static final Cleaner cleaner = Cleaner.create();\n\n    \/**\n     * An instance of Cleaner.Cleanable that the register returned.\n     *\/\n    final private Cleaner.Cleanable cleanable;\n\n    \/**\n     * The resource that should be cleaned after use.\n     *\/\n    final private CloseableResource resource;\n\n    public SampleResourceUsage() {\n        \/\/Instantiate a resource that must be cleaned after use.\n        resource = new CloseableResource();\n\n        \/\/Register with the cleaner.\n        cleanable = cleaner.register(this, resource::close);\n    }\n\n    public void use() {\n        resource.use();\n    }\n\n    @Override\n    public void close() {\n        \/\/Use clean method from the Cleanable instance to close the resource.\n        cleanable.clean();\n    }\n\n    public static void main(String ... args) throws InterruptedException {\n        \/\/Create an instance with cleanable resource.\n        var resource = new SampleResourceUsage();\n        resource.use();\n\n        \/\/Remove the instance reference.\n        resource = null;\n\n        \/\/Request for a garbage collection.\n        System.gc();\n\n        \/\/Try to wait for a garbage collection to complete.\n        \/\/If garbage collection was not triggered. Increase the timeout.\n        Thread.sleep(1000);\n    }\n\n    \/**\n     * The class that should have clean up operation.\n     *\/\n    private static class CloseableResource {\n        public void use() {\n            System.out.println(&quot;Using the resource that must be cleaned.&quot;);\n        }\n\n        \/**\n         * The cleaner that must be called for garbage collection.\n         *\/\n        public void close() {\n            System.out.println(&quot;Cleaning up.&quot;);\n        }\n    }\n}<\/code><\/pre>\n<p>Expect to see the following output:<\/p>\n<pre><code>Using the resource.\nCleaning up.<\/code><\/pre>\n<blockquote>\n<p>If you didn't see preceding output, you might need to check the timeout value.<\/p>\n<\/blockquote>\n<p>Here are some additional things to keep in mind when using Java Cleaner:<\/p>\n<ul>\n<li>The <code>Cleaner<\/code> object is a heavyweight object, so it should be shared whenever possible.<\/li>\n<li>The <code>Cleaner<\/code> thread is a daemon thread, so it will not prevent your program from exiting.<\/li>\n<li>The <code>clean()<\/code> method can only be called once. If you need to perform multiple cleanup actions, you should use a <code>Runnable<\/code> object to wrap the cleanup actions.<\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Java Cleaner is a new feature introduced in Java 9 that allows you to define cleanup actions for groups of objects. Cleaners are implemented with the Cleanable interface, which descends from Runnable. Each Cleanable represents an object and a cleaning action registered in a Cleaner. Each Cleanable runs in a dedicated thread. All exceptions thrown [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[79,43],"tags":[],"_links":{"self":[{"href":"https:\/\/www.ronella.xyz\/index.php?rest_route=\/wp\/v2\/posts\/1605"}],"collection":[{"href":"https:\/\/www.ronella.xyz\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.ronella.xyz\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.ronella.xyz\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.ronella.xyz\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=1605"}],"version-history":[{"count":2,"href":"https:\/\/www.ronella.xyz\/index.php?rest_route=\/wp\/v2\/posts\/1605\/revisions"}],"predecessor-version":[{"id":1607,"href":"https:\/\/www.ronella.xyz\/index.php?rest_route=\/wp\/v2\/posts\/1605\/revisions\/1607"}],"wp:attachment":[{"href":"https:\/\/www.ronella.xyz\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=1605"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.ronella.xyz\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=1605"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.ronella.xyz\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=1605"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}