Course contentsShow
← Java
Lesson 576 of 2,87013. The Object Class and Common MethodsFree lesson

Modern Alternatives to finalize

Learn proper resource cleanup using try-with-resources, AutoCloseable, and Cleaner API instead of finalize.

Modern Alternatives to finalize

What You'll Learn

You'll learn how to properly clean up resources using try-with-resources, the AutoCloseable interface, and the Cleaner API—the modern, reliable replacements for the deprecated finalize method.

The Problem with finalize

As you've learned, finalize is unreliable: you can't predict when (or even if) it will run, and it hurts performance. Java provides three better approaches for resource cleanup.

try-with-resources and AutoCloseable

The best solution for managing resources is the try-with-resources statement combined with the AutoCloseable interface. When you implement AutoCloseable, you define a close() method that releases your resources. Java automatically calls close() when the try block exits—guaranteed.

class FileHandler implements AutoCloseable {
    public FileHandler(String filename) {
        // Open file
    }
    
    @Override
    public void close() {
        // Clean up file resources
        System.out.println("File closed properly");
    }
}

// Usage: close() called automatically
try (FileHandler handler = new FileHandler("data.txt")) {
    // Use the handler
} // close() guaranteed to be called here

This is deterministic—cleanup happens exactly when the try block ends, not at some unknown future time.

The Cleaner API (Last Resort)

For rare cases where try-with-resources won't work, Java 9 introduced the Cleaner API. It's like a safety net—still non-guaranteed, but better structured than finalize. However, you should almost always prefer try-with-resources.

Why This Matters

Think of finalize as asking someone to "maybe clean up sometime later, possibly." Try-with-resources is like setting an alarm: cleanup happens at a specific, predictable moment.

Key Takeaway: Always use try-with-resources with AutoCloseable for resource cleanup—it's explicit, guaranteed, and performant, unlike the unreliable finalize method.