I wonder if this piece of code will cause memory leakage? because I still don’t know when is a texture should be disposed. should the texture disposed in the end of method? or dispose it separately after unused?
private void loadAssets() {
Texture texture = new Texture(Gdx.files.internal("data/controls.png"));
TextureRegion[] buttons = TextureRegion.split(texture, 64, 64)[0];
left = buttons[0];
right = buttons[1];
jump = buttons[2];
cubeControl = buttons[3];
cubeFollow = TextureRegion.split(texture, 64, 64)[1][2];
dpad = new TextureRegion(texture, 0, 64, 128, 128);
batch = new SpriteBatch();
batch.getProjectionMatrix().setToOrtho2D(0, 0, 480, 320);
}
and I don’t really understand. why does there’s still memory leakage in Java?
Looking at the source of
TextureRegion, it retains a reference to theTexturebut doesn’t really take “ownership” of it – it’s never going to dispose it itself.Going by that, you shouldn’t dispose of it at the end of the method, but you should dispose of it when
cubeFollow,cubeControlanddpadare both finished with – which I suspect will be when the instance itself is finished with. (That may or may not mean you need a finalizer – it depends whether you have some control over the lifetime of this object.)Note that you don’t need a separate field to store a reference to the
Texture– you can get it fromdpadusingdpad.getTexture().