3
\$\begingroup\$

I've been looking at the LibGDX framework, and certain classes such as Pixmap require to be disposed manually when you are no longer using them (call the dispose method).

I'm wondering, since this is Java, why did they not choose to dispose the resources on Pixmap finalization? That is, override the finalize method to automatically call dispose. If an object is finalized, then that means that the Garbage Collector determined no hard references to it, so clearly no one is using the Pixmap and it is fine to dispose it.

What particular advantages are there to calling it manually rather than use the finalization method?

\$\endgroup\$
  • \$\begingroup\$ This is likely a decision on the part of the API developers; objects that require finalization must be kept alive longer than objects that don't, which can have a negative impact on the GC profile of your application. \$\endgroup\$ – user1430 Jan 23 '14 at 0:34
3
\$\begingroup\$

You may want to read up on this SO question to get some background information. That is:

  • Java GC is nondeterministic
  • You cannot force the GC to run at a certain point, only give it hints to run (which it may ignore)

In libGDX (if not gamedev in general), this is bad for two reasons:

  • GC may sometimes run for a long time, causing a noticeable pause in the game
  • You may have limited memory resources, especially on mobile platforms, so you want to force some deallocations to occur at specific points

For these reasons, it's in your interest to avoid long GC runs during gameplay, which means controlling when you deallocate expensive resources such as those encapsulated by Pixmap, for example deallocating during loading screens.

|improve this answer|||||
\$\endgroup\$
1
\$\begingroup\$

LibGDX avoids a problem with android wherein the OpenGL context can simply vanish over the course of running the app. If that happens, video-memory assets are lost. LibGDX fixes this problem by keeping the original objects in normal ram. That doubles the memory cost, but it allows the video memory to be repopulated from the other copy.

But in order to keep those assets in memory, they must not be disposed of randomly by the GC. That's why the responsibility falls to the API user to dispose them manually.

|improve this answer|||||
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.