Module lessons (2/2)
Try-with-resources and AutoCloseable
Guaranteed automatic closure in LIFO order, AutoCloseable, suppressed exceptions and prevention of resource leaks.
What you'll learn in this lesson
- Replace the verbose manual closing
try / finallyblocks with thetry-with-resourcesconstruct (Java 7+). - Implement the
AutoCloseableinterface to make any custom resource securely closeable. - Understand the LIFO order of closing multiple resources and the suppressed exceptions mechanism (
getSuppressed()).
Overview
Unlike memory on objects (reclaimed by the garbage collector), system resources such as open files, JDBC connections, sockets and ExecutorService must be deterministically closed immediately after use.
With the old finally, you had to handle possible NullPointerException and risked masking the main exception with a possible error inside close(). With try (Risorsa r = ...), the JVM automatically generates a perfect and safe finally:
Sections covered in this lesson
- 11. Why the
finallyManual Was Fragile vstry-with-resources - 22. Implement
AutoCloseableon Custom Resources - 33. Multiple Resources and Reverse Order (LIFO)
- 44. Effectively Final Variables (Java 9+) and Suppressed Exceptions
- 5Try it yourself
Unlock "Try-with-resources and AutoCloseable" and the full Course Java curriculum
Guaranteed automatic closure in LIFO order, `AutoCloseable`, suppressed exceptions and prevention of resource leaks.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Course Java plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.