CKTIS / Java
AutoCloseable — closing resources
java.lang.AutoCloseable defines a resource-closing contract through close(). In try-with-resources, Java calls this method when leaving the block, including because of an exception, and closes multiple resources in reverse order.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
public interface AutoCloseable {
void close() throws Exception;
}
try (Resource resource = new Resource()) {
// Use resource.
}java.lang.AutoCloseable is an interface for objects that may hold resources requiring release, such as file handles. Merely writing implements AutoCloseable does not trigger closing: the object must be managed by try-with-resources or closed explicitly.
AutoCloseable.close has the signature void close() throws Exception. An implementation must be public and may declare a narrower exception or none at all. Unlike java.io.Closeable, whose close() declares IOException, AutoCloseable does not require idempotence: closing again may have side effects. Idempotence is nevertheless recommended.
try-with-resources closes successfully initialized, non-null resources in reverse declaration order, including when leaving through return or an exception. If the block and close() both throw, the generated addSuppressed call attempts to attach the closing exception to the primary exception. If both throw the same Throwable instance, that call throws IllegalArgumentException, even if suppression is disabled. If the instances differ and suppression is enabled, getSuppressed() on the primary exception includes the closing exception. If suppression is disabled, the closing exception is not attached and getSuppressed() returns an empty array.
The example simulates two resources without file or network access. It prints work first, followed by close second and close first. The implementation Resource.close() declares no exceptions, so main needs no handling for a checked closing exception.
Examples
public class Main {
static final class Resource implements AutoCloseable {
private final String name;
Resource(String name) {
this.name = name;
}
@Override
public void close() {
System.out.println("close " + name);
}
}
public static void main(String[] args) {
try (Resource first = new Resource("first");
Resource second = new Resource("second")) {
System.out.println("work");
}
}
}Result
work close second close first
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.