When should you prefer finalize (deprecated) and cleaners and when should you avoid it?

finalize, deprecated, cleaners, Java, object finalization, resource management
This article discusses the scenarios for using finalize (deprecated) and Cleaners in Java, outlining their advantages and disadvantages in terms of resource management and object finalization.

    // Example demonstrating the usage of Cleaner in Java
    import java.lang.ref.Cleaner;

    public class ResourceHandler {
        private static final Cleaner cleaner = Cleaner.create();
        private final Cleaner.Cleanable cleanable;

        public ResourceHandler() {
            // Register a cleanup action with the Cleaner
            cleanable = cleaner.register(this, () -> {
                // Cleanup logic goes here
                System.out.println("Cleaning up resources...");
            });
        }

        public void useResource() {
            System.out.println("Using resources...");
        }

        public void close() {
            // Explicitly cleaning up resources if needed
            cleanable.clean();
        }

        public static void main(String[] args) {
            ResourceHandler handler = new ResourceHandler();
            handler.useResource();
            handler.close(); // Clean resources manually
        }
    }
    

finalize deprecated cleaners Java object finalization resource management