On this page
AutoCloseable
Prev: `try with resources` | Up: builtins | Next: `RuntimeException`
Rel: builtins, Classes, Records & Sealed Hierarchies
Ref: Java Docs — AutoCloseable
Tags: #public #prog #java #builtins #tier/core
Availability
Built-in / java.lang (java.lang Interface) — available with zero import statements.
Syntax & Overview
public interface AutoCloseable { void close() throws Exception; }
Protocol enabling deterministic resource cleanup via try-with-resources.
Notes & Pitfalls
- Powers
try-with-resources: ImplementAutoCloseable(orCloseableforIOException-only) on any resource holding OS handles or locks. - Make
close()idempotent so calling it twice never fails.
Example
class TempResource implements AutoCloseable {
boolean closed = false;
@Override public void close() { closed = true; }
}
TempResource ref;
try (var r = new TempResource()) {
ref = r;
}
assert ref.closed;
Linked from
Related notes
- tuts/java/builtins/RuntimeException Linked here; links to this page; shared tags: #builtins, #java, #prog, #tier
- tuts/java/builtins/try_with_resources Linked here; links to this page; shared tags: #builtins, #java, #prog, #tier
- tuts/java/builtins Linked here; links to this page; shared tags: #builtins, #java, #prog
- tuts/java/builtins/finalize links to this page; shared tags: #builtins, #java, #prog, #tier
- tuts/interop/java_and_c_ffm_and_jni links to this page; shared tags: #java, #prog, #tier
- tuts/java/language_and_oop/classes_records_and_sealed_hierarchies Linked here; shared tags: #java, #tier
- tuts/java/language_and_oop/exceptions_and_resource_management links to this page; shared tags: #java, #tier
- tuts/java/builtins/enum shared tags: #builtins, #java, #prog, #tier
- tuts/java/builtins/final shared tags: #builtins, #java, #prog, #tier
- tuts/java/builtins/interface shared tags: #builtins, #java, #prog, #tier