Memory Management for Android Apps 笔记之 GC

本篇博文是在观看 Google I/O 2011 : Memory Management for Android App 所做的笔记之一,主要篇幅是传递演讲者 Patrick Dubroy 的观点,小部分则掺杂了自己的理解。这里的观点可能包含了谬误,或者是过时信息,因此建议读者如果英语能力尚可,则不妨直接观看原视频或者演示文稿,–需翻墙。

Memory Management for Android Apps

Memory Management for Android Apps

Android 日志是开发者审视系统、应用运行状况的得力助手,它就像是驾驶员面前的仪表盘,车辆的时速、里程、油量等数据关系到行驶安全,而日志中的 GC 信息则反馈了系统、应用健康状况,细心的开发者甚至可以判定是不是发生了内存泄漏。

以下是我截取到的三则 GC 信息,它们分别代表了三种常见场景。我曾相同代码在不同版本,比如2.2(Froyo), 2.3(Gingerbread)和4.0.2(Ice cream sandwich),发现 GC 信息变化比较大,这也印证了演讲者关于 Dalvik VM GC 在 2.3 和 3.0 发生了改变的说法。

GC_CONCURRENT freed 2234K, 35% free 9013K/13767K, external 821K/1435K, paused 9ms+9ms
GC_FOR_MALLOC freed 689K, 33% free 8959K/13319K, external 1451K/1688K, paused 82ms
GC_EXTERNAL_ALLOC freed 122K, 38% free 8460K/13511K, external 1519K/1519K, paused 78ms

从上面可以看出GC 信息可以分成几个部分,例如 Reason for GC、Amount freed 等,以下将它们拆分来看。

Reason for GC

演讲者共提到五种类型,其中 GC_EXPLICIT 不为提倡,比较少见,GC_HPROF_DUMP_HEAP 则在正常运行情况下不会发生。GC_CONCURRENT 则从 2.3 版本才出现。同时 GC_FOR_MALLOC 则去掉了“M”。

1. GC_CONCURRENT
Triggered by basically, as your heap starts to fill up. VM kick off the current garbage collection so that it can hopefully complete before the heap gets full.
2. GC_FOR_MALLOC / GC_FOR_ALLOC
VM don’t complete the concurrent collection in time and application has to allocate more memory. The heap was full, so VM had to stop and do a garbage collection.
3. GC_EXTERNAL_ALLOC
Externally allocated memory, like bitmap pixel data. It’s also used for NIO direct byte buffers. The external memory has gone away in honeycomb, and basically everything is allocated inside the Dalvik heap now.
Now this external memory has gone away in Honeycomb. Basically everything is allocated inside the Dalvik heap now. So you won’t see this in your log messages in Honeycomb and later.
4. GC_HPROF_DUMP_HEAP
When you do a hprof profile.
5. GC_EXPLICIT
When call system.gc, GC_EXPLICIT happen. Programmer should avoid doing this, and trust in the garbage collector.

Amount freed

The amount of memory that was freed on this collection

Heap statistics

xx% freed after the collection completed.

The 1st number is live objects

The 2nd number is the total heap size

External memory statistics

which is bitmap pixel data and also NIO direct byte buffers.

The 1st of number is the amount of external memory that your app has allocated

The 2nd number is a sort of soft limit. When you’ve allocated that much memory, we’re going to kick off GC.

这里,我有一个疑问就是,演讲者提到 2.3 以后 external memory 的数据(bitmap pixel data)被移动到了 Dalvik Heap,那么到底是什么数据保存到了这块法外之地?

Pause time

One short pause at the beginning of the collection and one most of the way through. Non-concurrent collections you will see a single pause time.

这里,我有一个疑问就是,非并发类 GC 只有一个耗时好理解,但为何并发类 GC 却有两个值,从字面上理解演讲者的话,就是有两个耗时,分别发生在开始时和结束时,那么中间值跑去哪里了?

Leave a comment

Your comment