-6

I am new to Java and I am developing a Minesweeper clone using a MVC architecture. I it is much easier to restart the game creating a new view like this:

model.restart(); 
view = new View (model);

Than coding a view.restart() method.

My view class it inherits from the JFrame Swing component.

The problem is, that after playing the game for a while, I get java.lang.OutOfMemoryError: unable to create new native thread.

I have tried calling the garbage collector to delete old views with System.gc, but it doesn't work, and maybe makes the problem to appear sooner.

Thank you for your help! Greetings from Spain!

jpuriol
  • 372
  • 2
  • 13

2 Answers2

0

I found the way to fix it!

There is method in the JFrame componet that allows you to "erase" a JFrame: dispose() which does the following according to the Java API:

Releases all of the native screen resources used by this Window, its subcomponents, and all of its owned children. That is, the resources for these Components will be destroyed, any memory they consume will be returned to the OS, and they will be marked as undisplayable.

So the right way to write my code should be:

view.dispose();
model.restart();
view = new View();

That fixes my memory leak.

jpuriol
  • 372
  • 2
  • 13
-2

See this post: How to force garbage collection in Java?

There is no way to force and immediate collection though as the garbage collector is non-deterministic.

You really cannot force it. The only thing you can do is adapt the way you code, as you mention there maybe is a better way to restart the game than to rebuild the model and the view.

Community
  • 1
  • 1
Houbie
  • 1,321
  • 1
  • 12
  • 25