Android的垃圾收集,释放内部对象的对象 [英] android garbage collector, freeing objects inside objects

查看:370
本文介绍了Android的垃圾收集,释放内部对象的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对这个事情是如何工作的Andr​​oid里面很好奇。我有两个名单,一类LT;>里面,在运行时实例化,并装载在阅读一些数据创建的对象,我想知道这些名单在这种情况下发生的:

I'm very curious about how this thing works inside Android. I have a class with two List<> inside, instantiated at runtime and loaded with objects created while reading some data, I want to know what happens with those Lists in this situation:


  1. A类具有列表B和C组与其他许多初始化的对象
    里面。

  1. Class A has List B and List C with many other initialized objects inside.

另一个不同的类从拿到C组的参考
A类,方法如公开名单&LT;&myObject的GT;的GetList()

Another different class get a reference of List C from a method of Class A, like public List<myObject> GetList().

在某处code,A级不再使用与应用
信号,为垃圾收集器,设置对象为null。

Somewhere in code, Class A is no longer used and application signals that to garbage collector, setting object to null.

与通过其他对象引用我的C组名单会发生什么?与对象类,会发生什么?

What happens with my List C that is referenced by other object? What happens with Object class A?

我试图追踪logcat的运行APK垃圾收集器在调试程序一步一步,但没有运气可言。有时它释放内存,有时没有,我不能确定的任何具体行为。

I've tried to track garbage collector with Logcat running apk in debugger step-by-step but no luck at all. Sometimes it frees memory, sometimes not, I couldn't pinpoint any specific behaviour.

推荐答案

如果有任何对象,仍然有根目录的路径,包括到另一个对象的引用,被引用的对象不会被垃圾收集。所以,如果你创建一个对象,具有子对象A1。然后创建对象B,通过什么都意味着通过A1的引用对象B.即使对象A GC'd A1会不会因为对象B仍持有的参考。 (在你的榜样,A和B将被gc'd。C不会)

If there is any object, that still has a path to root, containing a reference to another object, the referenced object will not be garbage collected. So if you create object A, that has a sub object A1. Then create object B and through what ever means pass a reference to A1 to object B. Even when object A is GC'd A1 will not be because object B still holds a reference. (In your example, A & B will be gc'd... C will not)

您可以通过显式地告诉系统在某些时候用 System.gc()的执行收集垃圾回收背后的力学实验。你也可以覆盖的finalize对象看给定对象收集的确切时间:

You can experiment with the mechanics behind garbage collection by telling the system explicitly to perform a collection at certain times with a System.gc(); call. Also you can override the finalize in object to see exactly when the given object is collected.:

   @Override
   protected void finalize() throws Throwable {
      try {
         Log.d("Learning about GC", "My Object has been GC'd." + this);         
      } finally {
         super.finalize();
      }
   }

您可以通过与对象,引用实验学到很多东西,最终确定和GC显式调用()。当你完成测试后,我会删除重写的敲定电话。

You can learn a lot through experimenting with objects, references, finalize and explicit calls for gc(). I would remove the overridden finalize call when you done testing.

这篇关于Android的垃圾收集,释放内部对象的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆