Is disposing SXSSFWorkbook necessary when used in try with resource
Asked Answered
R

3

6

Below is the sample code snippet to create SXSSFWorkbook:

try(SXSSFWorkbook wb = new SXSSFWorkbook()) {
    //...
} finally {
    wb.dispose(); //wb not accessible over here, so can't use try with resource
}

Here problem is that if I use try with resource then can't dispose() SXSSFWorkbook in finally, as variable wb won't be accessible in finally block.

I wanted know that is disposing of workbook necessary to delete temporary files or since SXSSFWorkbook is AutoCloseable, try with resource will take care of it.

Rival answered 15/5, 2018 at 13:32 Comment(0)
R
6

Not sure whether someone of the apache poi programmers will answering this. But apache poi is open source. So every programmer can answering this itself by looking at the code.

State May 2018, apache poiversion 3.17.

SXSSFWorkbook.java:

public class SXSSFWorkbook implements Workbook

So why can this be a resource for using in try with resource? Because

Workbook.java:

public interface Workbook extends Closeable, Iterable<Sheet>

So org.apache.poi.ss.usermodel.Workbook extends java.io.Closeable and so classes which implements this must providing a method close.

SXSSFWorkbook.close

As you see, the single SheetDataWriters will be closed and then the internally XSSFWorkbook _wb will be closed.

SheetDataWriter.close

SheetDataWriter.close only flushes and closes the Writer _out.

So no, nowhere the dispose is called while auto closing until now (May 2018) in apache poiversion 3.17

And only SheetDataWriter.dispose will deleting the TempFile _fd created for each sheet.

Rhaetic answered 16/5, 2018 at 5:47 Comment(0)
B
3

This is a forrmal resolution of the problem.

SXSSFWorkbook t_wb = null;
try(SXSSFWorkbook wb = t_wb = new SXSSFWorkbook()) {
    //...
} finally {
    if(t_wb != null) t_wb.dispose();
}
Beach answered 30/7, 2019 at 17:44 Comment(1)
Apache's example doesn't bother calling close on the workbook. Which leaves me wondering is it really needed or is the example just lacking. I loath such errant examples as the bad pattern gets replicated over and over by people naively thinking it's good.Scheers
P
2

This question bothers me too, so my solution is to override the close method, like this:

//a utility method somewhere
Workbook createMyCustomWorkbook() {
    return new SXSSFWorkbook() {
        public void close() throws IOException {
            try {
                dispose();
            } catch (Exception e) {
                //some logging
            }
            super.close();
        }
    };
}


//use in a simple try catch block
try(Workbook wb = createMyCustomWorkbook())
    //do stuff with wb
}
Plenipotentiary answered 27/1, 2023 at 9:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.