How to clear up the heap

I’ve been at this all day and am not making progress. I need a way to swap areas in my game which would then dump all the stuff not needed which includes sound effects and textures mostly. Then it will load up the new textures and things.

I have a class with one variable screen which is a Screen type. When I want to switch, I set the current screen = null and then load up a new Screen type. Screen is an abstract class and I have two subclasses.

So it looks something like this


public class Game extends JPanel implements Runnable {
	
	private Screen mScreen;
	
	public Game() {
		mScreen = new ScreenPrison(); // ScreenPrison extends Screen
	}
	
	private void run() {
		mScreen.update();
		mScreen.render(g);
		mScreen.swap();
		// ---- ---- swap is this ---- ----
		//	Graphics g2 = getGraphics();
		//	g2.drawImage(bImage, 0, 0, WIN_WIDTH, WIN_HEIGHT, null);
		//	g2.dispose();
		// ---- ---- end ---- ----
	}
	
	public void swapScreen(Screen screen) { // call this method with swapScreen(new ScreenTitle());      
        //where ScreenTitle extends Screen
		mScreen = null;
		mScreen = screen;
	}
}

public abstract class Screen {

        private Game mGame;

	public Screen(Game g) { // need this to call swapScreen()
	     mGame = g;
	}
	
	public void update() {
		// does some things here that are shared among different types of screens 
		// but I do override the method in the subclass and tack on different stuff
		// and also call super.update(); from the subclass
	}
	
	public abstract void render(Graphics2D g);
	
}
	
	
	
}

I thought by switching the reference as is done in swapScreen() that ScreenPrison plus everything inside that class file would be picked up by the GC…
Any help is much appreciated.

Hi!

What’s the question exactly?
If you need to load up a new screen, why not do currentScreen = new Screen(…);
Assets in the current screen will be collected by Java’sgarbage collector automatically : )

That’s what I’ve tried doing but all the old assets that were created in the old screen don’t get collected

You can hint the GC to clean garbage up for you by setting all objects you want cleaned up to null
(not sure if this is still a thing tho)