Search code examples
javalibgdxdestructordispose

How to use dispose() properly?


For example, if I have an instance of an object, which implements Disposable, let's say it is

BitmapFont someFont = new BitmapFont();

According to LibGDX documentation, I should call the dispose() method as soon as the object is no longer needed. But what if decide to assign new font to the same variable:

someFont = new BitmapFont();

Should I first call dispose() before such an assignment in order to prevent a memory leak? In other words, which variant is correct, this

    BitmapFont someFont = new BitmapFont();
    //do something
    someFont.dispose();
    someFont = new BitmapFont();
    //do something else
    someFont.dispose();

or this:

    BitmapFont someFont = new BitmapFont();
    //do something
    someFont = new BitmapFont();
    //do something else
    someFont.dispose();

I'm currently thinking that the first one is correct, and it seemes that dispose() behaves just like the destructor in C++, except for the fact that it is not called automatically.

So, which version is actually correct?


Solution

  • Your variable is simply a pointer to a given object, not an overarching container that holds all references that it has ever encompassed. If you were to follow your second code example, you are only calling dispose on the second BitmapFont instance, not the first one. Your first pattern is technically correct, and you would want to consider try/finally blocks as well to ensure dispose is called when you are done with it.