TheProjectCodex
TheProjectCodex

Reputation: 79

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?

Upvotes: 2

Views: 1729

Answers (2)

Peter Berg
Peter Berg

Reputation: 6206

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.

Upvotes: 0

ata
ata

Reputation: 9011

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

Upvotes: 5

Related Questions