Determine when the Android GC runs

2019-03-31 05:25发布

Does anyone know if there is a way to identify (in code, not LogCat) when the GC has run? 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.

2条回答
Evening l夕情丶
2楼-- · 2019-03-31 05:47

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().

I don't think the GC would have a hook to tell you what it's doing though. 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?

查看更多
看我几分像从前
3楼-- · 2019-03-31 06:04

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.

查看更多
登录 后发表回答