I have a level manager for my game I'm working on, and it's supposed to unload the previous level, and then load the next level. However, when I test it (though I'm not sure I'm testing it right) the memory usage seems to go up when I switch levels multiple times.
public final class LevelManager implements KeyControllable {
private LevelList levels;
private int currentLevel;
public LevelManager(final int width, final int height) {
levels = new LevelList(width, height, this);
currentLevel = 0;
}
public void goToLevel(final LEVEL level) {
levels.unloadLevel(currentLevel);
for (int i = 0; i < LEVEL.values().length; i++) {
if (LEVEL.values()[i] == level) {
currentLevel = i;
}
}
levels.getLevel(currentLevel).reset();
}
public void draw(final Graphics2D g) {
levels.getLevel(currentLevel).draw(g);
}
public void update() {
levels.getLevel(currentLevel).update();
}
@Override
public void keyPressed(final KeyEvent e) {
if (levels.getLevel(currentLevel) instanceof KeyControllable) {
((KeyControllable) levels.getLevel(currentLevel)).keyPressed(e);
}
}
@Override
public void keyReleased(final KeyEvent e) {
if (levels.getLevel(currentLevel) instanceof KeyControllable) {
((KeyControllable) levels.getLevel(currentLevel)).keyReleased(e);
}
}
public enum LEVEL {
LEVEL_ONE(LevelOne.class), LEVEL_TWO(LevelOne.class);
Constructor<? extends AbstractLevel> level;
private LEVEL(final Class<? extends AbstractLevel> level) {
try {
this.level = level.getDeclaredConstructor(int.class, int.class, LevelManager.class);
} catch (NoSuchMethodException | SecurityException e) {
e.printStackTrace();
}
}
}
private static class LevelList {
private AbstractLevel[] levels;
final private int width, height;
final private LevelManager levelManager;
public LevelList(final int width, final int height, final LevelManager levelManager) {
this.width = width;
this.height = height;
this.levelManager = levelManager;
LEVEL[] levelList = LEVEL.values();
levels = new AbstractLevel[levelList.length];
}
public void unloadLevel(int i) {
levels[i] = null;
}
public AbstractLevel getLevel(final int i) {
if (levels[i] == null) {
try {
levels[i] = LEVEL.values()[i].level.newInstance(width, height, levelManager);
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
e.printStackTrace();
}
}
return levels[i];
}
}
}
I was using this to test the used memory:
System.out.println(Runtime.getRuntime().totalMemory());
Is there a memory leak in this program? (other tips would be appreciated as well)