How to get the garbage collector to work?

10-11  Source: Network gathering  Views:0 

i have i program where i load an image scale it down and save the scaled version in an array. I do this for a whole directory of images.
After every image i set the temporary variable for the loaded image = null and call the function System.gc().
My problem is, that the garbage collector does�nt give the memory of the loaded image free and the used memory of my program grows with every loaded image.
/* Reads all images from a folder an stores them in an Array of images */
     public static BufferedImage[] readScaledImagesFromFolder(String folder,
               int maxSize) {
          File dir = new File(folder);     /* Open the Folder */
          String[] children = dir.list();          /* Get the children of the folder */
          if (children == null) {
             // Either dir does not exist or is not a directory
              System.out.println("No images in the folder!");
              return null;
         } else {
              /* Init array for images */
              BufferedImage[] images = new BufferedImage[children.length];     
              int i = 0;
              int index = 0;
              BufferedImage temp;
              String filename, fileending;
             for (i=0; i<children.length; i++) {
                  // Get filename of file or directory
                 filename = children;
     /* Get the fileending of the file */
     fileending = filename.toLowerCase().substring(filename.length()-4);
     if(fileending.equals(".jpg") || fileending.equals(".bmp")
               || fileending.equals(".png") || fileending.equals(".gif"))
          /* Read the image */
          temp = util.ImageUtils.loadBufferedImage(folder+"/"+filename);
          /* Scale the image down and save it in an array */
          images[index] = Util.getScaledImage(temp,maxSize);
     temp = null;
     Mosaic.sourceImageNum = index;
     System.out.println((index+1)+" resized pictures loaded from folder: "+folder);
     return images;     
How can i get the gargabe collector to work after every iteration?
I tried to let the Thread.sleep(10) after System.gc() but it does�nt help.
Thank you every much
Hm yes.. i now that System.gc() is only a
But i know what my program is doing and that it
does�nt need the temporary image anymore after i have
a scaled down version. And the temporay image will become unreachable as soon as reading the next one overwrites your temp variable. Setting the variable to null doesn't have much effect.
It would be smarter to load the new image over the
old temporary image and not to expand the heapsize to
maximum.Then look at the possibitly of loading the next image into the same bufferedimage.
Related articles