Home

AutoCloseable

AutoCloseable is an interface in java.lang introduced in Java 7 to standardize resource management. It declares a single method close() throws Exception. Implementing classes represent resources that must be released when no longer needed.

AutoCloseable is the superinterface of Closeable; Closeable is a subinterface whose close() method declares IOException. Thus,

With try-with-resources, resources declared in the try parentheses are automatically closed at the end of the

Best practices: resources should be final or effectively final to use in the try-with-resources statement. The

Example: try (AutoCloseableResource r = new AutoCloseableResource()) { r.doWork(); } // r.close() executes automatically.

all
Closeable
resources
are
AutoCloseable,
but
not
all
AutoCloseable
resources
are
Closeable.
The
interface
enables
the
try-with-resources
statement.
block.
They
are
closed
in
reverse
order
of
creation.
If
an
exception
is
thrown
within
the
try
block,
and
a
second
exception
is
thrown
during
close,
the
latter
is
added
as
a
suppressed
exception
to
the
primary
one.
close
method
may
throw
a
checked
exception,
hence
the
declaration.
In
practice,
many
standard
resources
implement
Closeable.