Skip to content

Commit d77a4cc

Browse files
[Effective Java] Item 9: Prefer try-with-resources to try-finally
1 parent 9cf8038 commit d77a4cc

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

Java/Effective Java/2 Creating and Destroying Objects.md

+34
Original file line numberDiff line numberDiff line change
@@ -207,3 +207,37 @@ Mosaic create(Supplier<? extends Tile> tileFactory) { ... }
207207
* “So what should you do instead of writing a finalizer or cleaner for a class whose objects encapsulate resources that require termination, such as files or threads? Just **have your class implement `AutoCloseable`**, and require its clients to invoke the `close` method on each instance when it is no longer needed, typically using `try`-with-resources to ensure termination even in the face of exceptions (Item 9).”
208208
* “One detail worth mentioning is that the instance must keep track of whether it has been closed: the `close` method must record in a field that the object is no longer valid, and other methods must check this field and throw an `IllegalStateException` if they are called after the object has been closed.”
209209
* **“In summary, don’t use cleaners, or in releases prior to Java 9, finalizers, except as a safety net or to terminate noncritical native resources.”**
210+
211+
## Item 9: Prefer `try`-with-resources to `try`-`finally`
212+
213+
* “Historically, a try-finally statement was the best way to guarantee that a resource would be closed properly, even in the face of an exception or return.”
214+
215+
```java
216+
// try-finally - No longer the best way to close resources!
217+
static String firstLineOfFile(String path) throws IOException {
218+
    BufferedReader br = new BufferedReader(new FileReader(path));
219+
    try {
220+
        return br.readLine();
221+
    } finally {
222+
        br.close();
223+
    }
224+
}
225+
```
226+
227+
* “To be usable with the `try`-with-resources statement, a resource must implement the AutoCloseable interface, which consists of a single void-returning `close` method.”
228+
229+
```java
230+
// try-with-resources on multiple resources - short and sweet
231+
static void copy(String src, String dst) throws IOException {
232+
    try (InputStream   in = new FileInputStream(src);
233+
         OutputStream out = new FileOutputStream(dst)) {
234+
        byte[] buf = new byte[BUFFER_SIZE];
235+
        int n;
236+
        while ((n = in.read(buf)) >= 0)
237+
            out.write(buf, 0, n);
238+
    }
239+
}
240+
```
241+
242+
* **“Always use `try`-with-resources in preference to `try`-`finally` when working with resources that must be closed. The resulting code is shorter and clearer, and the exceptions that it generates are more useful.”**
243+

0 commit comments

Comments
 (0)