Idempotent close() Implementation
What you'll learn: How to write close() methods that can be safely called multiple times without causing errors or unexpected side effects.
When you implement the AutoCloseable interface, you need to write a close() method. But here's an important question: what happens if someone calls close() twice on the same resource? An idempotent close() method handles this gracefully—calling it multiple times has the same effect as calling it once.
Why Idempotency Matters
Think of idempotent close() like turning off a light switch. If the light is already off and you flip the switch again, nothing bad happens—it just stays off. Your close() method should work the same way: closing an already-closed resource should be safe and harmless.
This matters because:
- Try-with-resources might call
close()automatically - A programmer might explicitly call
close()before the try block ends - Exception handling paths could inadvertently call
close()multiple times
Writing an Idempotent close()
The pattern is simple: track whether the resource is already closed, and return early if it is.
public class DatabaseConnection implements AutoCloseable {
private boolean closed = false;
@Override
public void close() throws Exception {
if (closed) {
return; // Already closed, do nothing
}
// Perform actual cleanup
// ... release resources ...
closed = true; // Mark as closed
}
}
Without this check, calling close() twice might try to release resources that are already released, potentially throwing exceptions or causing undefined behavior.
Key Takeaway: Always make your close() methods idempotent by checking if the resource is already closed before performing cleanup—this prevents errors when close() is called multiple times.