Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Java: Fix memory leak

I have a memory leak in my java game application, that I was somehow expecting. The leak comes from a new instance being created multiple times on this button action listener, because each time I press the button it creates a new instance of RegularMode:

btnRegular.addActionListener(new ActionListener() {
 @Override
 public void actionPerformed(ActionEvent e) {
 frame.remove(pane);
 gm = Gamemode.REGULAR;
 mode = new RegularMode(frame, WIDTH, HEIGHT);
 }
});

Funny thing is, I have been trying to fix the memory leak, using this code:

public static void initDisplay() {
 gm = Gamemode.NONE;
 mode.setRunning(false);
 frame.remove(mode.getPane());
 frame.add(pane);
 frame.validate();
 frame.repaint();
 mode = null; // THIS LINE
 frame.pack();
}

– but it doesn't work. Are there any other ways to solve this type of memory leak?

Answer*

Draft saved
Draft discarded
Cancel
2
  • Yes, this is true. It also merely requests that the JVM garbage collect, and doesn't force it to. Commented Nov 2, 2013 at 22:18
  • It's generally best to not expect System.gc() to do anything at all predictable. It's mostly there for people who feel they must somehow control GC, even when they don't have the foggiest notion what they're doing. Commented Nov 2, 2013 at 23:12

lang-java

AltStyle によって変換されたページ (->オリジナル) /