Search code examples
androidlibgdxdispose

Importance of the dispose method (libgdx)


I'm just getting started with Android Game Development and I'm testing the libgdx Framework at the moment. I was just wondering what the importance of the dispose() method is and why it is necessary to dispose of every object there? Just to save resources?

Appreciate it.


Solution

  • Java is a "managed language". This means that everything (e.g. instances of classes or arrays) you use in your application automatically gets destroyed when you no longer use it. This is done by the "garbage collector". So, when you create e.g. an array (float[] arr = new float[1000];) then you allocate memory, but you never have to free that memory yourself because the garbage collector will do that for you when you no longer use the array (arr).

    In some cases, however, the garbage collector can't know how to automatically free something for you. For example, when you allocate some space in video memory (VRAM) then you don't have access to that memory directly, but instead use the graphics driver to use that memory. For example (pseudo code):

    byte[] image = loadImageFromDisk();
    int vramId = graphicsDriver.allocateMemory(image.length);
    graphicsDriver.copyToVRAM(vramId, image);
    image = null;
    ...
    // At this point the garbage collector will release the memory used by "image".
    // However, the allocated VRAM still contains a copy of the image, so you can still use it.
    ...
    graphicDriver.showImageOnScreen(vramId);
    ...
    // The garbage collector can't free the VRAM though, you need to manually free that memory.
    ...
    graphicsDriver.releaseMemory(vramId);
    

    So, practically, there are two kind of resources in this case.

    1. Resources that will be automatically released by the garbage collector. Let's call those: managed resources.
    2. Resources that can't be automatically released by the garbage collector. Let's call those: native resources.

    As you probably can imagine, libgdx uses quite alot of native resources behind the scenes. To properly manage those resources libgdx contains the Disposable interface. Every class that implements this Disposable interface uses (directly or indirectly) native resources that can't be released automatically by the garbage collector. Therefor you need to manually call the dispose methods on those classes if you no longer need them.

    Not calling the dispose method can potentially result into problems with native resources. E.g. you might run out of available video memory or alike, causing your application to crash or alike. This is most commonly referred to as a "memory leak".