What is finalize (deprecated) and cleaners in Java?

In Java, the finalize method was used to perform cleanup operations before an object is garbage collected. However, it is now deprecated due to several issues, including unpredictability in timing and performance impacts. Instead, Java introduced the concept of cleaners, which provides a more reliable way to clean up resources when an object is no longer in use.

The Cleaner class provides a mechanism to register cleanup actions that can be executed when the object becomes unreachable. This ensures that resources are released at the appropriate time without the unpredictability associated with the finalize method.

Here is a simple example of using a Cleaner in Java:

import java.lang.ref.Cleaner; public class Resource { private static final Cleaner cleaner = Cleaner.create(); private final Cleaner.Cleanable cleanable; public Resource() { cleanable = cleaner.register(this, () -> System.out.println("Cleaning up resource.")); } // Additional resource management code public void close() { cleanable.clean(); } } public class Main { public static void main(String[] args) { Resource resource = new Resource(); resource.close(); // Explicit cleanup } }

finalize cleaners Java resource management garbage collection