Re: heap memory issue, related with garbage collection
Thank you for all your replies.
My original post missed some information which now is critical. My program =
has two buttons besides other buttons: one button is "Next" and one button =
is "ContinueouslyPlay". When clicking button "ContinueouslyPlay", a child t=
hread is repeatedly calling displayPic() with incremented parameter. The co=
de above works well since all the variables are local - so the thread 'see'=
the new objects without problem. The problem is out of heap memory when re=
aching picture 150.(If clicking "Next" button, it is the main thread displa=
ying next picture only - very simple.)
Now, I have changed those variables to class instance variables. Now concur=
rent programming adds the complexity: in "ContinueouslyPlay" mode, very oft=
en the displayed one remain unchanged for quite a bit even though the title=
is showing the next, next etc picture file names. So the child thread does=
not 'see' the new stuff. I have added 'volatile' keyword to the instance v=
ariables. No help. There is no out of heap memory error any more. But such =
no displaying is more annoying. Here is the code(I think using a separate t=
hread for "ContinueouslyPlay" mode is reasonable and I don't want to change=
it. Otherwise all other buttons are not responsive):
public class PictureDisplayer implements ActionListener {
private final JFrame _jFrame;
private final JPanel _jPanel;
private volatile JLabel _picLabel;
private volatile JPanel _picPanel;
private volatile ImageIcon _imageIcon;
..
public PictureDisplayer() throws Exception
{
_jFrame = new JFrame();
_jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
_jFrame.setSize(Constants.MONITOR_WIDTH, Constants.MONITOR_HEIGHT);
_jPanel = new JPanel(new BorderLayout());
//Create the toolbar.
final JToolBar toolBar = new JToolBar("Still draggable");
//Lay out the main panel.
_jPanel.setPreferredSize(new Dimension(Constants.MONITOR_WIDTH, Con=
stants.MONITOR_HEIGHT));
_jPanel.add(toolBar, BorderLayout.PAGE_START);
_picLabel = new JLabel();
_picPanel = new JPanel();
_runThread = new Thread(new Runnable() {
public void run() {
while(true) {
displayPic(++_picCount);
try {
Thread.sleep(10000);
}
catch(final Exception e) {//hopefully never happen
}
}
}
});
..
}
private void displayPic(final int picCount)
{
String pngFileNameWithPath = xxx; //create PNG file name from pic=
Count
_imageIcon = new ImageIcon(pngFileNameWithPath);
_picLabel.setIcon(_imageIcon);
_picPanel.add(_picLabel);
_jPanel.add(_picPanel, BorderLayout.CENTER);
_jFrame.getContentPane().add(_jPanel);
_jFrame.setTitle(pngFileNameWithPath);
_jFrame.setVisible(true);
}
public void actionPerformed(final ActionEvent evt) {
..
}
}
Thank you very much.