title: Java - BufferedImage (ImageIO.Read) OutOfMemory Heap Space
body: <p>Ok, so I am getting an Out of Memory (Heap Space) error in my code, and I have figured out (with profiling) that the error is coming from the creation of images.</p>
  
  <p>What I have is a class that creates an image into a smaller one, and then that class will be painted.</p>
  
  <p>The problem is that if I want to load up 1000+ of these images into JPanels, I get to around 750 before it taps out, and I don't really want to extend the memory of java.</p>
  
  <p>Heres the code:</p>
  
  <pre><code>class Foo extends JPanel{
  private BufferedImage image;
  private Image scaled;   
  public Foo(String link){
      try{
          setPreferredSize(new Dimension(50,50));
          image = ImageIO.read(new URL(link)); //Cause for memory leak
          scaled= image.getScaledInstance(100, 140, BufferedImage.SCALE_FAST);
          image.flush();
                      //tried image = null; but did not help memory
      }
      catch(Exception e){}
  }
  
  public void paintComponent(Graphics g){
      super.paintComponent(g);
      g.drawImage(scaled, 5, 5, null);
  }
  }
  </code></pre>
  
  <p>So basically, is there a more efficient way to read a link into an image, or some how remove unnecessary memory?</p>