简体   繁体   中英

Garbage collector not running even with very low memory on Android

I am developing an Android game which uses TMX tiled maps. While the maps are being loaded, the memory usage of the application rises to over 100MB. After each map is loaded, I hint for the garbage collector to run (using System.gc() ) and, unsurprisingly, the amount of memory in use does not decrease at all. I understand that calling the System.gc() method does not ensure the garbage collector to run, but I would expect it to considering the maximum VM heap size on my device is around 130MB (and as low as 16-20MB on other, older devices). As one would expect, when another map is loaded after this, the application throws an out of memory error and crashes.

However, I can ensure that my code has no memory leaks or unreleased resources as when I force the GC to run using the DDMS heap tab in Eclipse ('Cause GC' button), the application's memory usage drops back down to around 15-16MB.

Is there anything I have missed that could be causing the retaining of the excessive over 100MB memory usage when loading maps?

It would be good to actually see how are you dealing with the loading of the images.

I assume that you are using the Bitmap class to deal with them. You have to bear in mind that this class is a bit more special under the hood. It is actually wrapping around a native implementation that represents bitmaps as byte arrays. Garbage Collection won't help you in this case (further more it's a bad practice to rely on GC being executed in a particular point in time). I think you should take a closer look at the recycle() method of the Bitmap class. It releases the native object, occupied by the bitmap instance.

The Javadoc states that it's an advanced call and, normally, it shouldn't be triggered manually, since the GC will do this if there are no more references to the Bitmap instance, but in my experience with images in Android (also game development), sometimes it helps you in these kind of situations.

Another advice I can give you is to heavily profile the heap of your app - maybe the maps are not the only culprit. I would try tracing the memory allocations in DDMS and check for potential red flags there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM