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?
2 Answers 2
I am not sure how you came to concluding that the code you provided is causing the memory leak. Use some profiler to see what objects are currently in heap and accumulating. You can search for profilers or check this: http://jyops.blogspot.se/2012/09/java-memory-model-simplified.html
Comments
You could try adding a call to System.gc() after setting mode to null.
You also could try using a different garbage collector than the default. To do so, pass in -XX:[Garbage collector] (e.g. -XX:ConcMarkSweep) when running your app. If you're in Eclipse, you have to set this in your project configuration (arguments to pass to the JVM). There is a list of the available collectors here.
You also can increase the cap on the amount of memory the jvm can use which default to something like 256mb. To do this you have to pass in -Xmx 1024M (or something like that).
Hope this helps.
2 Comments
Explore related questions
See similar questions with these tags.
actionListeneralone cannot create a leak, because Java is garbage-collected. Normally, when you assign to mode, its old value should become eligible for collection. So, you should try to explain why it does not become eligible.WeakReferences rather than normal ones, so they cannot prevent stale values from being garbage-collected.modefield, and try to understand why references are not made garbage-collectable.