Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

AutoCloseable.close(): explicit and automatic resource cleanup

`AutoCloseable.close()` releases a resource. Call it on an object yourself, or let `try-with-resources` call it automatically when the block exits.

Version: Java SE 21

Syntax

void close() throws Exception;

resource.close();

try (AutoCloseable resource = acquireResource()) {
    // Use the resource here.
} catch (Exception e) {
    // Handle the exception.
}

In Java SE 21, AutoCloseable.close and AutoCloseable.close() name the same instance method of java.lang.AutoCloseable. It takes no arguments and returns nothing (void). To release a resource explicitly, call the method on the object: resource.close().

Use try-with-resources when a resource should be closed when you leave a block. Java attempts to close successfully initialized, non-null resources in reverse initialization order, even if the block throws or a later resource fails to initialize. Don't manually close a resource that the same statement will close: AutoCloseable does not guarantee idempotence. By contrast, java.io.Closeable.close() has no effect on an already closed resource.

The interface declares throws Exception, but an implementation can declare a narrower checked exception or none. For explicit and automatic calls, catch or declare the checked exceptions based on the resource's compile-time type. If both the block and cleanup throw, the block's exception normally stays primary. The cleanup exception can be recorded as suppressed and retrieved through getSuppressed() only if suppression is enabled on the primary exception. If there is no earlier exception, the cleanup exception propagates.

Examples

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Main {
    private static final class Subscription implements AutoCloseable {
        private final List<Subscription> active;
        private final boolean failOnClose;

        Subscription(List<Subscription> active, boolean failOnClose) {
            this.active = active;
            this.failOnClose = failOnClose;
            active.add(this);
        }

        @Override
        public void close() throws IOException {
            if (active.remove(this) && failOnClose) {
                throw new IOException("simulated close failure");
            }
        }
    }

    public static void main(String[] args) {
        List<Subscription> active = new ArrayList<>();

        try (Subscription temporary = new Subscription(active, true)) {
            Subscription manual = new Subscription(active, false);
            System.out.println("Active before manual close: " + active.size());
            manual.close();
            System.out.println("Active after manual close: " + active.size());
        } catch (IOException e) {
            System.out.println("Caught: " + e.getMessage());
        }

        System.out.println("Active after try: " + active.size());
    }
}

Result

Active before manual close: 2
Active after manual close: 1
Caught: simulated close failure
Active after try: 0

`Subscription` is an example class, not part of the standard API. `manual.close()` removes just one subscription. Automatic cleanup removes the temporary subscription, then throws a simulated `IOException` that the `catch` block handles.

Related lessons

  • Java · Lesson 47 · Advanced · Version: 2
  • Java · Lesson 52 · Basic · Version: 2

Sources