I am trying to merge 1000 PDF Files thru iText. I am not sure where the memory leakage is happening. Below is the sample code. Note that i am removing the child-pdf file as soon as i merge to the parent file. Please pointout bug in below code or is there any better way to do this with out memory conception. This process is done thru servlet (not standalone program)
FileInputStream local_fis = null;
BufferedInputStream local_bis = null;
File localFileObj = null;
for(int taIdx=0;taIdx<totalSize;taIdx++){
frObj = (Form3AReportObject)reportRows.get(taIdx);
localfilename = companyId + "_" + frObj.empNumber + ".pdf";
local_fis = new FileInputStream(localfilename);
local_bis = new BufferedInputStream(local_fis);
pdfReader = new PdfReader(local_bis);
cb = pdfWriter.getDirectContent();
document.newPage();
page = pdfWriter.getImportedPage(pdfReader, 1);
cb.addTemplate(page, 0, 0);
local_bis.close();
local_fis.close();
localFileObj = new File(localfilename);
localFileObj.delete();
}
document.close();
OutOfMemoryError: Metaspace error is thrown. To mitigate the issue, you can increase the size of the Metaspace by adding the -XX:MaxMetaspaceSize flag to startup parameters of your Java application. For example, to set the Metaspace region size to 128M, you would add the following parameter: -XX:MaxMetaspaceSize=128m .
OutOfMemoryError is a runtime error in Java which occurs when the Java Virtual Machine (JVM) is unable to allocate an object due to insufficient space in the Java heap. The Java Garbage Collector (GC) cannot free up the space required for a new object, which causes a java. lang. OutOfMemoryError .
lang. OutOfMemoryError: Java heap space. This error can be solved by manually adding a parameter to dedicate memory to the build process.
You might want to try something like the following (exception handling, file close and delete removed for clarity):
for(int taIdx = 0; taIdx < totalSize; taIdx++) {
Form3AReportObject frObj = (Form3AReportObject)reportRows.get(taIdx);
localfilename = companyId + "_" + frObj.empNumber + ".pdf";
FileInputStream local_fis = new FileInputStream(localfilename);
pdfWriter.freeReader(new PdfReader(local_fis));
pdfWriter.flush();
}
pdfWriter.close();
Who says there is a memory leak? Your merged document needs to fit into memory in its entirety, there's no way around it, and it may well be larger than the default heap size of 64MB in memory (rather than on disc).
I don't see a problem with your code, but if you want to diagnose it in detail, use visualvm's heap profiler (comes with the JDK since Java 6 update 10 or so).
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