4

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.

1
  • 2
    try-with-resoures will only call close on passed in AutoCloseable. In fact you can only use AutoCloseable objects with try-with-resoures. POI objects implement AutoCloseable, but their close and dispose methods are different. See SXSSFWorkbook close: "Closes the underlying XSSFWorkbook and OPCPackage on which this Workbook is based, if any." dispose: "Dispose of temporary files backing this workbook on disk. Calling this method will render the workbook unusable." Commented Sep 30, 2024 at 21:06

2 Answers 2

6

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 implement java.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.

Sign up to request clarification or add additional context in comments.

Comments

6

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.