Takeaway: We know that in Java, the JVM automatically calls the GARBAGE collector (GC) to collect objects that are not referenced in the heap. It is not clear when the garbage collector will be collected, and the JVM will not collect objects that are used by other resources, like a FileInputStream that uses disk resources. The garbage collector does not collect, so it must be turned off manually. The JDK has Closeable and AutoCloseable options for releasing resources, as described below.
Closeable
Closeable source
Use close with caution
InputStream, outputStream, Reader, Writer and other base classes in the java.io. Package implement the Closeable interface because resources are released after each I/O operation.
-
If the stream is closed before this method is called, the method is invalidated;
-
You are advised to close internal resources and mark them as closed.
-
Throw AN IO exception first;
AutoCloseable
The AutoCloseable interface is in the java.lang package and was introduced starting with JDK1.7.
Because it’s in the java.lang package, it’s available for all streams that implement the interface, and closable itself implements the interface. Java I/o streams can optionally close the interface automatically, meaning that starting with jdk1.7, streams don’t need to be closed manually.
AutoCloseable source
{try}-with-resources
Prior to 1.7, we freed resources in finally via try{} finally{}.
- Closing a resource in finally has the following problems:
- Write your own manual code to do the logic of closing;
- Sometimes you forget to close resources;
- The logic of closing code is verbose and should not be a concern of normal business logic;
It’s obviously cumbersome. {try}-with-resources {try}-with-resources
Put a block of code that might throw an exception into a try block, and when the try ends, those resources are automatically closed (by calling the close method).
{the try} – with – resources is the key point
Three key points for a try statement with a resource:
- Resources managed by the try statement with resources must be objects of classes that implement the AutoCloseable interface.
- Resources declared in the try code are implicitly declared final.
- You can manage multiple resources by separating each declaration with a semicolon.
Doesn’t that look easy and comfortable
What is the difference between Closeable and AutoCloseable?