Course contentsShow
← Java
Lesson 822 of 2,87020. Try-With-Resources and Resource ManagementFree lesson

What is AutoCloseable?

Understanding the AutoCloseable interface and its role in automatic resource management.

What is AutoCloseable?

You'll learn: What the AutoCloseable interface is and how it enables automatic cleanup of resources in Java.

The Core Idea

AutoCloseable is a simple Java interface that marks an object as capable of being automatically closed when you're done with it. Think of it like a door that can shut itself — once you've walked through, the door knows how to close behind you without you manually turning back to shut it.

When a class implements AutoCloseable, it promises to provide a close() method that cleans up whatever resources it holds (like file handles, database connections, network sockets, etc.). This single method is the contract: "I know how to clean up after myself."

Why Does This Matter?

Before AutoCloseable, developers had to manually close resources in finally blocks — tedious and error-prone. You'd write try-catch-finally structures to ensure files got closed even when exceptions occurred. With AutoCloseable, Java can automatically call close() for you at the right time, making resource management much safer and cleaner.

The Interface

public interface AutoCloseable {
    void close() throws Exception;
}

That's it! Just one method. Any class implementing this interface must provide its own close() implementation that releases whatever resources it manages.

Real-World Analogy

Imagine a library book with a special RFID tag. When you leave the library, the gate automatically logs your checkout. The AutoCloseable interface is like that RFID tag — it signals, "I'm a resource that needs cleanup, and I know how to do it."

Key Takeaway: AutoCloseable is an interface with a single close() method that enables objects to participate in automatic resource management, ensuring resources are properly released without manual cleanup code.