AutoCloseable vs Closeable
What you'll learn: You'll understand the key differences between the AutoCloseable and Closeable interfaces and when each is used.
The Two Interfaces for Resource Management
Java has two interfaces for objects that need cleanup: AutoCloseable (introduced in Java 7) and the older Closeable (from Java 5). Both define a close() method, but they serve slightly different purposes.
Key Differences
Closeable is specifically designed for I/O resources like files and streams. It:
- Extends
AutoCloseable - Declares
close()to throw onlyIOException - Is idempotent by convention (calling
close()multiple times should be safe)
AutoCloseable is the more general parent interface for any resource that needs cleanup. It:
- Declares
close()to throwException(broader) - Works with try-with-resources
- Makes no idempotency guarantee
- Can be used for non-I/O resources (database connections, locks, etc.)
The Relationship
Think of it like vehicle types: AutoCloseable is like "vehicle" (general category), while Closeable is like "car" (specific type with stricter rules). All Closeable objects are AutoCloseable, but not all AutoCloseable objects are Closeable.
Since Closeable extends AutoCloseable, any I/O class implementing Closeable automatically works with try-with-resources and follows the stricter I/O conventions (like safe multiple closes and throwing only I/O-related exceptions).
For non-I/O resources—like database connections or custom resource managers—implementing AutoCloseable directly gives more flexibility in what exceptions close() might throw.
Key Takeaway: Closeable is a specialized version of AutoCloseable for I/O operations with stricter contracts (idempotent, IOException only), while AutoCloseable is the general-purpose interface for any resource cleanup in try-with-resources.