Skip to content

Commit

Permalink
perf($POI): close workbook when destroying locale context
Browse files Browse the repository at this point in the history
  • Loading branch information
johnnymillergh committed Mar 1, 2021
1 parent 7d31473 commit ebebd3e
Showing 1 changed file with 23 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
Expand Down Expand Up @@ -268,13 +269,31 @@ private void destroyLocaleContext() {
sheetLocation.remove();
readingRowCount.remove();
userDefinedMessage.remove();
closeWorkbook(workbook.get());
workbook.remove();
closeWorkbook(workbookWithErrorMessage.get());
workbookWithErrorMessage.remove();
excelFilePath.remove();
exceptionOccurred.remove();
file.remove();
}

/**
* Close workbook.
*
* @param workbook the workbook
*/
private void closeWorkbook(Workbook workbook) {
if (workbook != null) {
try {
workbook.close();
} catch (IOException e) {
log.error("Exception occurred when closing workbook! Exception message: {}, workbook: {}",
e.getMessage(), workbook);
}
}
}

/**
* Upload excel file. Any exceptions happened in any lifecycle will not interrupt the whole process.
*
Expand Down Expand Up @@ -577,13 +596,13 @@ public static void main(String[] args) {
private Workbook readFile(@NonNull File file) throws IOException {
Workbook workbook = null;
val extension = FilenameUtils.getExtension(file.getName());
val bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
if (XLS.equals(extension)) {
FileInputStream fileInputStream = new FileInputStream(file);
POIFSFileSystem poifsFileSystem = new POIFSFileSystem(fileInputStream);
POIFSFileSystem poifsFileSystem = new POIFSFileSystem(bufferedInputStream);
workbook = new HSSFWorkbook(poifsFileSystem);
fileInputStream.close();
bufferedInputStream.close();
} else if (XLSX.equals(extension)) {
workbook = new XSSFWorkbook(new FileInputStream(file));
workbook = new XSSFWorkbook(bufferedInputStream);
}
return workbook;
}
Expand Down

0 comments on commit ebebd3e

Please sign in to comment.