-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
  • 362
  • 2
  • 14
  • All we can say from your question is that you indeed have a leak. You should use a monitor to find out which thread does not get cleaned up. – Fildor Dec 29 '15 at 18:40
  • You need to take care that previous methods/function calls ended so that the GC can clean up. – Norbert Dec 29 '15 at 18:41
  • So, there is no actual way of forcing Java to delete a reference that no longer exists? – jpuriol Dec 29 '15 at 19:40

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
  • 362
  • 2
  • 14
-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,406
  • 1
  • 13
  • 25