Reputation: 918
In my project, I have a module to upload multiple image and create the thumbnails for it at once. For uploading, I am using JavaFX and for creating thumbnails, I am using Java.
I wrote upload code and call of thumbnail creation function inside a for loop. If the number of uploading images is more than five, I am getting this error:
Java heap space (java.lang.OutOfMemoryError)
I think, the code for uploading is fine, and the problem with thumbnail creation code. How can I solve this problem? How should I change the structure of my code ?
This is my JavaFX code:
fgUrl = fc.getSelectedFiles();
for(fg in fgUrl) {
try {
System.gc();
fileURL = "file:///{fg.toString()}";
fileURL = fileURL.replace("\\", "/");
def dt = DateTime{}.instant;
var datetime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:SSS").format(dt);
pic_url = datetime.replace("-", "_").replace(":", "_").replace(" ", "_");
datetime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(dt);
f = new File("C:\\uploaded\\{pic_url}.jpg");
uploadFile(fileURL, f,save_index,datetime,pic_url); // This function will save selected image in the working directory of the system.
var resize_ob = new resizeImage(url.replace("file:///", ""),"C:/thumbnails/{pic_url2}.jpg");// This will call the java thumbnail creation function.
save_index++;
}
catch(e:Exception) { }
}
Upvotes: 2
Views: 1963
Reputation: 13666
You can try to use memory profilers to see which portion of code/class/method is consuming more memory. You can start with free JVisualVM or JConsole which comes with JDK.
Other well known profilers are:
-> Optimize IT
-> JProfiler
Upvotes: 3
Reputation: 1221
As long as you have a reference to these images(in a variable or inside List or something) the Java's automatic Garbage Collector wont clean it up. You should only load them when you need them, then set the variables to null as soon as you're finished with each image.
Images are pretty big, and Java probably unpacks them to bitmaps(like bmp files, huge) so this is not a surprise.
Garbage collection doesn't run constantly (it cleans up every so often), so if you want to ask it to run now (you can't force it) you can call System.gc();. Garbage collection is slow though, so it may slow your processing.
If needed you can increase your maximum memory, but its better practice to do the above.
With more information i can supply a more detailed answer.
Upvotes: 2