I have been using try-with-resources a lot. I use it for database resource types or File
stuff all the time to close the resource.
Now, I am using POI for large Excel files, and I am just noticing that I should call workbook.dispose()
. Will try-with-resources call the dispose()
method? Everything I looked up only covers close()
.
No, try-with-resources only works for objects that implement java.lang.AutoCloseable
. That interface defines a single method: close()
. That close
method is the one and only method called by the try-with-resources syntax.
To quote the tutorial on try-with-resources:
Any object that implements
java.lang.AutoCloseable
, which includes all objects which implementjava.io.Closeable
, can be used as a resource.
Any dispose()
method is not automatically called. However, the developers of these classes/libraries might have decided to call dispose()
in their implementation of the close()
method or vice versa. In that case both "clean up" methods would do the same.