Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does try-with-resources call dispose() method? [duplicate]

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.

like image 672
Sedrick Avatar asked Oct 16 '25 04:10

Sedrick


2 Answers

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.

like image 78
Cardinal System Avatar answered Oct 17 '25 17:10

Cardinal System


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.

like image 20
Progman Avatar answered Oct 17 '25 17:10

Progman