Skip to content Skip to sidebar Skip to footer

Static Variables, Libgdx And Android Pause/resume Memory Usage

Program example: public class main extends ApplicationAdapter { public static int a; public static int b; public static Player player; public void create() {

Solution 1:

The life-cycle of static references is not the same as the life-cycle of your application. In other words, it is possible that multiple instances of your application use the same static variable.

If you set a static variable to null in a method of your application then you will set it to null for all instances of your application running in the same VM. Setting a reference to null, however does not mean that the memory is actually free'd. Only when there are no other references to the same object and the garbage collector is run, then the object will removed.

That said, please note that the pause and resume methods are not the correct methods to do something like that. In fact, for above reasons you should never use the static keyword at all for things that are specific to one instance of your application, unless you are properly managing those static references. For example, libgdx does this behind the scenes by keeping a map of the instances of your application and the resources they use. This allows you to have "managed resources" which are automatically reloaded when needed (which is the default).

In your case that would be over complicating things and it's easier to simply remove the static keyword. This typically also forces you to have a better OO design as well and not use shortcuts like e.g. the singleton pattern which will usually lead to other issues on the long run as well.

Solution 2:

create new static variables or just assign values to the old static variables that was is in memory ?

Only assign value to a, b by resume() method.

Static variables are initialized only once , at the start of the execution.

EDIT

You're creating new object of Player and assigning to player reference variable. After that you don't have reference of old player object so when JVM feel need to run garbage collector, garbage collector will run and clear memory of old player object.

Post a Comment for "Static Variables, Libgdx And Android Pause/resume Memory Usage"