Re: heap memory issue, related with garbage collection
I solved my problem.
Here is my original code:
private void displayPic(final int picCount)
{
String pngFileNameWithPath = xxx; //get PNG file name based on in=
t picCount
final ImageIcon imageIcon = new ImageIcon(pngFileNameWithPath);=
final JLabel picLabel = new JLabel();
picLabel.setIcon(imageIcon);
final JPanel picPanel = new JPanel();
picPanel.add(picLabel);
_jPanel.add(picPanel, BorderLayout.CENTER);
_jFrame.getContentPane().add(_jPanel);
_jFrame.setTitle(pngFileNameWithPath);
_jFrame.setVisible(true);
}
The problem is when this method was called 150 times, then heap memory ran =
out. I found the cause is that at the end of the method, even though those =
references('picLabel', 'picLabel' etc) are out of scope and dead, the objec=
ts that once were referenced by them were not garbage collected and that wa=
s due to that those objects, even though not referenced by 'picLabel', 'pic=
Label' etc, were still referenced by some other references. In order to mak=
e those objects really collected by JVM garbage collection, I added these c=
ode near the end of the method:
picLabel.removeAll();
picPanel.removeAll();
_jPanel.remove(picPanel);
_jFrame.getContentPane().remove(_jPanel);
I am not sure if they all are needed or if one is covering another. But any=
way, I can keep all references inside the method(no need to make them class=
instance variables) and no more memory issue.