简体   繁体   English

确定Android GC何时运行

[英]Determine when the Android GC runs

Does anyone know if there is a way to identify (in code, not LogCat) when the GC has run? 有没有人知道GC运行时是否有办法识别(在代码中,而不是LogCat)? Perhaps an intent is fired? 也许一个意图被解雇了? I could analyze the LogCat output, but it would be ideal if I could determine when the GC has run from my code. 我可以分析LogCat输出,但如果我可以确定GC何时从我的代码中运行,那将是理想的。

You can do this with a weak reference trick: 你可以用一个弱参考技巧来做到这一点:

WeakReference<GcWatcher> mGcWatcher
        = new WeakReference<GcWatcher>(new GcWatcher());
long mLastGcTime;

class GcWatcher {
    @Override
    protected void finalize() throws Throwable {
        handleGc();
        mLastGcTime = SystemClock.uptimeMillis();
        mGcWatcher = new WeakReference<GcWatcher>(new GcWatcher());
    }
}

Now... whether it is really correct for an application to do this, is another thing. 现在......对于应用程序来说,这是否真的正确,是另一回事。 :) The only place I know of anywhere we have done this in Android is the code here, and its sole purpose is to help us be smart about when we ask processes to explicitly GC such as when they go into the background. :)我知道在Android中我们所做的任何地方的唯一地方就是这里的代码,它的唯一目的是帮助我们明智地询问流程何时明确GC,例如当他们进入后台时。

The garbage collector won't run until all of your threads are suspended. 在所有线程都挂起之前,垃圾收集器不会运行。 Since phones are pretty low memory environments, it's probably safe to assume that the GC is going to run after you receive an onPause() or onStop(). 由于手机是相当低的内存环境,因此可以安全地假设在收到onPause()或onStop()后GC将运行。

I don't think the GC would have a hook to tell you what it's doing though. 我不认为GC会有一个钩子来告诉你它在做什么。 You would probably have to allocate memory to be told that a collection happened. 你可能不得不分配内存来告诉收集发生了。

I'm curious, if your program had this information, what would it do with it? 我很好奇,如果你的程序有这些信息,它会用它做什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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