Implementing AutoCloseable
What you'll learn: How to create your own classes that automatically clean up resources using Java's AutoCloseable interface.
The Core Idea
Implementing AutoCloseable means writing a class that Java can automatically clean up when used in a try-with-resources statement. You simply add implements AutoCloseable to your class declaration and provide a close() method that handles cleanup logic.
This is powerful for any resource that needs cleanup: database connections, file handles, network sockets, or even custom resources like locks or temporary data structures.
How to Implement AutoCloseable
Your class needs three things:
- Declaration: Add
implements AutoCloseableto your class - The close() method: Write
public void close()(or allow it to throwException) - Cleanup logic: Put your resource cleanup code inside
close()
Example structure:
public class MyResource implements AutoCloseable {
public MyResource() {
// Initialize your resource
System.out.println("Resource acquired");
}
@Override
public void close() {
// Clean up your resource
System.out.println("Resource released");
}
}
Now you can use it in try-with-resources:
try (MyResource resource = new MyResource()) {
// Use the resource
System.out.println("Using resource");
} // close() is called automatically here
Making close() Idempotent
A best practice is making close() safe to call multiple times (idempotent). Check if cleanup is needed before doing it:
@Override
public void close() {
if (alreadyClosed) {
return;
}
// Perform cleanup
alreadyClosed = true;
}
Key Takeaway: Implementing AutoCloseable means adding implements AutoCloseable to your class and writing a close() method that performs cleanup, enabling automatic resource management with try-with-resources.