I have an out of memory exception when working with javax.Swing
and here's what I did.
I loaded 16 jpgs (70*70 pixels each) and had 16 Jbuttons
. I set the ImageIcon
of the JButtons
to different jpgs very quickly in a loop, basically as quickly as my CPU can handle . The memory usage is increased radically. The problem is, I never reloaded image. There are only 16 images and all the assignments are passed by reference right? I run Eclipse Memory Analyzer and here's what I got:
One instance of "java.awt.image.FilteredImageSource" loaded by " < system class loader > " occupies 703,066,368 (43.58%) bytes. The instance is referenced by sun.awt.image.ToolkitImage @ 0x7859cef60 , loaded by " < system class loader > ". The memory is accumulated in one instance of "java.util.Hashtable$Entry[]" loaded by "< system class loader >".
Keywords
java.awt.image.FilteredImageSource
java.util.Hashtable$Entry[]
Can I suspect there's a memory leak in Java's swing implementation? Any ideas?
Basically the code looks like:
public class Test{
private static ImageIcon[] imgIcon;
private static JButton[] buttons;
private static JFrame myFrame;
public static void main(String[] args){
myFrame = new JFrame(new GridLayout());
for(int i = 0; i < 16; i ++){
imgIcon[i] = //load the imageIcons
buttons[i] = new JButton();
myFrame.add(buttons[i]);
}
myFrame.pack();
myFrame.setVisible(true);
new Thread(new Runnable(){
@Override
public void run(){
while(true){
for(int i = 0; i < 16; i ++){
SwingUtilities.invokeAndWait(new Runnable(){
public void run(){
buttons[i].setIcon(imgIcon[/*random num 1-16*/]);
});
}
}
}
}).start();
}
}
Please disregard the apparent anti-pattern here because I abstracted away a lot of things going on in the new thread.