Skip to content Skip to sidebar Skip to footer

Waiting For Gc To Finish Before Starting Game With Java?

I'm making a fast-paced realtime Android game, and everything works great, but the first couple of seconds when the game starts are very laggy because the garbage collector is clea

Solution 1:

This seems like a case where System.gc() might help. It tells the system that this would be a good time to collect garbage. According to the documentation,

When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects.

The docs also say, though, that the method "suggests" that objects be collected -- that is, there's no guarantee it'll help, particularly if you still have some references squirreled away. If it does work, it'll only collect objects that are not reachable at all from the running code, including the runtime. (That loader thread, for example, is not eligible for collection til it's finished running and your code has no more references to it.)

Solution 2:

You can run System.gc() right before you start the game to manually force the garbage collector to run (and, according at least to the official JavaDoc here, finish before returning from this method call). However, the GC in general is nondeterministic and there is no guarantee that it will not be run again or, for that matter, that the call to System.gc() will do anything at all.

Solution 3:

If you looked into this more deeply you will probably find that much (even most) of the "lagginess" is not the GC's fault. I suspect that it is mostly due to JIT compilation. Calling System.gc() could improve things, but I doubt that it will get rid of the lagginess entirely.

Post a Comment for "Waiting For Gc To Finish Before Starting Game With Java?"