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()
.
I am not convinced that the duplicate is the same question. My question specifically asks if Dispose
is handled by try-with-resource
. None of the other questions mention Dispose
.
Try-with-resources only supports the AutoClosable
interface and will only call the close()
method. You can read more into it here.
You do have the option of using a wrapper (if necessary) which would implement AutoClosable
and call dispose()
in the close()
method. Here is a basic example (not tested):
public class WorkbookResource implements AutoCloseable {
private SXSSFWorkbook workbook;
public WorkbookResource(SXSSFWorkbook workbook) {
this.workbook = workbook;
}
// Delegate methods
@Override
public void close() throws Exception {
workbook.dispose();
workbook.close();
}
}
I do not know very much about Apache POI, but you may want to verify if calling both close
and dispose
is necessary.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With