Sub topic 12
AutoCloseable and Closeable
The last chapter showed that a resource is anything your program borrows and must give back, such as an open file or a network connection. You also saw that closing it by hand in a finally block takes care and is easy to get wrong. Java fixes this with a simple agreement: every resource class offers one method, close(), that gives the resource back. This chapter looks at that agreement and at the two interfaces that define it.
What the interfaces are
An interface is a list of methods that a class promises to provide. Java has two interfaces for things that can be closed:
AutoCloseablelives in the packagejava.lang, so you never need to import it. It was added in Java 7. It has one method:void close() throws Exception.Closeablelives in the packagejava.io. It is older (Java 5) and is used for input and output classes. It also has one method:void close() throws IOException.
Since Java 7, Closeable extends AutoCloseable. That means every Closeable is also an AutoCloseable. Java looks for AutoCloseable when it closes resources for you automatically, so any class with either interface works there.
Comparing the two
| Feature | `AutoCloseable` | `Closeable` |
|---|---|---|
| Package | `java.lang` (no import) | `java.io` (needs import) |
| Added in | Java 7 | Java 5 |
| `close()` may throw | `Exception` | `IOException` |
| Calling `close()` twice | Should be safe, but not required | Must be safe (required) |
| Typical users | Database connections, locks, your own classes | Files, streams, readers, writers |
There are two differences to remember.
The first is the exception type. Closeable.close() can only throw IOException, which is a narrower type than Exception. That makes life easier for whoever calls it, because they only have to handle one kind of checked exception.
The second is calling close() more than once. The documentation for Closeable says that a second call to close() must do nothing. This property has a name: idempotent. An idempotent action gives the same result whether you do it once or many times. AutoCloseable only recommends this, but you should do it anyway.
Classes you already know
You have already used many classes that implement these interfaces:
BufferedReader,FileReader, andFileWriterimplementCloseable.FileInputStreamandFileOutputStreamimplementCloseable.ScannerimplementsCloseable.java.sql.Connection(a database connection) implementsAutoCloseable.ExecutorService(a pool of threads) implementsAutoCloseablesince Java 19.
If you aren't sure whether a class needs closing, check its documentation for "All Implemented Interfaces". If AutoCloseable or Closeable is in that list, you should close it.
Writing your own AutoCloseable class
You can make your own class closeable. Here is a pretend network connection. It prints messages so you can see when it opens and closes.
public class CloseDemo {
static class Connection implements AutoCloseable {
private final String name;
private boolean closed = false;
Connection(String name) {
this.name = name;
System.out.println("open " + name);
}
void send(String message) {
if (closed) {
throw new IllegalStateException(name + " is closed");
}
System.out.println(name + " sends: " + message);
}
@Override
public void close() {
if (closed) {
return;
}
closed = true;
System.out.println("close " + name);
}
}
public static void main(String[] args) {
Connection conn = new Connection("server-1");
try {
conn.send("hello");
} finally {
conn.close();
}
conn.close();
System.out.println("done");
}
}Running it prints:
open server-1
server-1 sends: hello
close server-1
doneHere is what each part does:
implements AutoCloseablepromises that the class has aclose()method.- The
closedfield remembers whether the connection was already closed. close()returns at once ifclosedis alreadytrue. That makes it idempotent, so the second call inmainprints nothing.send()throws anIllegalStateExceptionif someone uses the connection after closing it. This catches bugs early.
Notice that our close() has no throws clause at all, even though AutoCloseable.close() says throws Exception. When a class overrides a method, it may throw fewer exceptions than the original, but never more. Because our close cannot fail, we left the clause off. Code that holds a Connection variable can now call close() without any try or catch.
Writing your own Closeable class
When your resource does input or output, implement Closeable instead. This example collects lines of text and "saves" them when it is closed. Saving can fail, so close() declares IOException.
import java.io.Closeable;
import java.io.IOException;
public class ReportDemo {
static class Report implements Closeable {
private final StringBuilder lines = new StringBuilder();
private boolean closed = false;
void add(String line) {
if (closed) {
throw new IllegalStateException("report is closed");
}
lines.append(line).append('\n');
}
@Override
public void close() throws IOException {
if (closed) {
return;
}
closed = true;
if (lines.length() == 0) {
throw new IOException("nothing to save");
}
System.out.print("saving report:\n" + lines);
}
}
public static void main(String[] args) {
Report report = new Report();
try {
report.add("sales: 120");
report.add("returns: 4");
} finally {
try {
report.close();
} catch (IOException e) {
System.out.println("save failed: " + e.getMessage());
}
}
}
}Running it prints:
saving report:
sales: 120
returns: 4If you delete the two add lines, close() throws, and the program prints save failed: nothing to save instead.
The finally block here holds a second try and catch just to call close(). That nesting is the clumsy pattern from the previous chapter. The next chapter replaces all of it with one short statement.
Rules for a good close() method
Follow these rules when you write close():
- Release everything. Give back every file, connection, or lock the object holds.
- Make it safe to call twice. Use a flag such as
closed, as both examples do. - Mark the object as closed first. Set
closed = truebefore the work that might fail. Then a failed close isn't retried in a half-finished state. - Reject use after close. Throw
IllegalStateExceptionfrom other methods once the object is closed. - Avoid
InterruptedException. The Java documentation warns against throwing it fromclose(), because it can confuse code that handles thread interruptions.
Which interface should you choose?
Use these questions:
- Does your class read or write data, like a stream or file? Implement
Closeable. - Is it some other resource, such as a lock, a timer, or a connection? Implement
AutoCloseable. - Can closing never fail? Either interface works. Leave off the
throwsclause in yourclose().
Either choice lets Java close your object automatically, which is the topic of the next chapter.
Exercise
What is the relationship between Closeable and AutoCloseable, and what exception can each close() method throw?
Show answer
Closeable extends AutoCloseable, so every Closeable is also an AutoCloseable. AutoCloseable.close() is declared to throw Exception, and Closeable.close() is declared to throw IOException.
Exercise
In the CloseDemo program, why does the second call to conn.close() print nothing?
Show answer
The close() method checks the closed flag first. The first call sets closed to true, so the second call returns right away. This makes close() idempotent, which means calling it again has no further effect.
Exercise
Write a class Timer that implements AutoCloseable. Its constructor prints "start" and its close() prints "stop". Callers must not need to catch any exception when they call close().
Show answer
public class Timer implements AutoCloseable { public Timer() { System.out.println("start"); } @Override public void close() { System.out.println("stop"); } }. The close() method has no throws clause, which is allowed because an override may throw fewer exceptions than the interface method.